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
JavaScript
x
27
27
1
import React, { useState } from "react";
2
import StudentForm from "./StudentForm";
3
import StudentList from "./StudentList";
4
5
const StudentListResult = () => {
6
const [newStudent, setNewStudent] = useState("");
7
const [students, setStudentsList] = useState([]);
8
9
return (
10
<div>
11
<div>
12
<StudentForm
13
newStudent={newStudent}
14
setNewStudent={setNewStudent}
15
students={students}
16
setStudentsList={setStudentsList}
17
/>
18
</div>
19
<div>
20
<StudentList students={students} setStudentsList={setStudentsList} />
21
</div>
22
</div>
23
);
24
};
25
export default StudentListResult;
26
27
StudentListForm
JavaScript
1
33
33
1
import React from "react";
2
import { v4 as uuidv4 } from "uuid";
3
4
const StudentListForm = ({
5
newStudent,
6
setNewStudent,
7
students,
8
setStudentsList,
9
}) => {
10
const addStudent = (event) => {
11
event.preventDefault();
12
setStudentsList([students, { id: uuidv4(), name: newStudent }]);
13
setNewStudent("");
14
};
15
return (
16
<form onSubmit={addStudent}>
17
<div>
18
<input
19
value={newStudent}
20
type="text"
21
placeholder="Student Name"
22
onChange={(e) => setNewStudent(e.target.value)}
23
/>
24
</div>
25
<div>
26
<button>Submit</button>
27
</div>
28
</form>
29
);
30
};
31
32
export default StudentListForm;
33
StudentList.jsx
JavaScript
1
17
17
1
import React from "react";
2
3
const StudentList = ({ students = [], setStudentsList }) => {
4
return (
5
<div>
6
{students.map((student) => (
7
<ul key={student.id}>
8
<li>
9
<p>{student.name}</p>
10
</li>
11
</ul>
12
))}
13
</div>
14
);
15
};
16
export default StudentList;
17
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.
JavaScript
1
8
1
const StudentListResult = () => {
2
const [submitted, setSubmitted] = useState(false)
3
4
return (
5
{submitted ? <StudentList /> : <StudentListForm />}
6
);
7
};
8
And then in your addStudent
function, set submitted
.
JavaScript
1
5
1
const addStudent = (event) => {
2
// ...
3
setSubmitted(true)
4
}
5