Skip to content
Advertisement

Conditional Component Rendering using UseState

I have a form in a page, when the user inputs the name of a new student and clicks submit, I want the content of that component (the form) to be completely replaced by the submitted name. How can I achieve this (Replace the form with the list onsubmit)?

I have read that I can use conditional rendering to toggle components, but it’s not really clear to me how i can apply it here.

StudentListResult.Jsx

import React, { useState } from "react";
import StudentForm from "./StudentForm";
import StudentList from "./StudentList";

const StudentListResult = () => {
  const [newStudent, setNewStudent] = useState("");
  const [students, setStudentsList] = useState([]);

  return (
    <div>
      <div>
        <StudentForm
          newStudent={newStudent}
          setNewStudent={setNewStudent}
          students={students}
          setStudentsList={setStudentsList}
        />
      </div>
      <div>
        <StudentList students={students} setStudentsList={setStudentsList} />
      </div>
    </div>
  );
};
export default StudentListResult;

StudentListForm

import React from "react";
import { v4 as uuidv4 } from "uuid";

const StudentListForm = ({
  newStudent,
  setNewStudent,
  students,
  setStudentsList,
}) => {
  const addStudent = (event) => {
    event.preventDefault();
    setStudentsList([...students, { id: uuidv4(), name: newStudent }]);
    setNewStudent("");
  };
  return (
    <form onSubmit={addStudent}>
      <div>
        <input
          value={newStudent}
          type="text"
          placeholder="Student Name"
          onChange={(e) => setNewStudent(e.target.value)}
        />
      </div>
      <div>
        <button>Submit</button>
      </div>
    </form>
  );
};

export default StudentListForm;

StudentList.jsx

import React from "react";

const StudentList = ({ students = [], setStudentsList }) => {
  return (
    <div>
      {students.map((student) => (
        <ul key={student.id}>
          <li>
            <p>{student.name}</p>
          </li>
        </ul>
      ))}
    </div>
  );
};
export default StudentList;

Advertisement

Answer

So you want to show the form if not submitted and show the list if submitted? You can add a piece of state called submitted and do simple conditional rendering.

const StudentListResult = () => {
  const [submitted, setSubmitted] = useState(false)

  return (
    {submitted ? <StudentList /> : <StudentListForm />}
  );
};

And then in your addStudent function, set submitted.

const addStudent = (event) => {
  // ...
  setSubmitted(true)
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement