Reputation: 29
I am trying to generate a new form when you click a button. I want to do this with hooks. I am struggling to wrap my head around what I need to do, below is an example function and the button. Any help is appreciated.
const addStudent = () => {
console.log("clicked")
return(
<Container>
<Form form="First Name" type="text" placeholder="First Name"/>
<Form form="Last Name" type="text" placeholder="Last Name"/>
<Form form="Date of Birth" type="date"/>
<Form form="School ID" type="text"/>
<Form form="Campus" type="text"/>
<Form form="School Grade" type="text"/>
</Container>
)
console.log(setStudent)
}
<button onClick={addStudent}>Add Another Student</button>
Upvotes: 1
Views: 5653
Reputation: 29
I created a variable called students and using Context for capturing the state values. I then mapped through students and then for the addStudent function just used the spread operator and set setStudents below.
const [students, setStudents] = useContext(FormDataContext);
*this is in the return()*
{students.map((student, index) => (
<FormCard
key={index}
index={index}
handleChange={handleChange}
student={students[index]}
metadata={metadata}
/>
))}
*then called this function in my button onClick*
const addStudent = () => {
setStudents([...students, {}]);
};
Upvotes: 0
Reputation: 3589
You can do something like this
https://codesandbox.io/s/silly-nash-0slhh?file=/src/App.js:97-1145
App.js
import Input from "./Input";
export default function App() {
const [students, setStudents] = useState([]);
const addStudent = () => {
setStudents(students => [...students, <Input />]);
console.log("dddd", students);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={addStudent}>Add Another Student</button>
{students.map((item, i) => (
<div key={i}>{item}</div>
))}
</div>
);
}
Input.js
import React, { useState } from "react";
export default function Input() {
const [firstName, setFirstName] = useState("");
const [lastName, setLastname] = useState("");
const [Dob, setDob] = useState("");
return (
<div style={{ width: "200px", height: "100px", padding: "5px" }}>
<input
type="text"
value={firstName}
onChange={e => setFirstName(e.target.value)}
placeholder="First Name"
/>
<input
type="text"
value={lastName}
onChange={e => setLastname(e.target.value)}
placeholder="Last Name"
/>
<input
type="text"
value={Dob}
onChange={e => setDob(e.target.value)}
placeholder="DOB"
/>
</div>
);
}
Upvotes: 1