The state variables are -
const [details, setDetails] = useState({
Name: "",
Number: null,
subject= [{
subject1 : "",
subject2 : ""
}]
})
<input type="text" placeholder="Enter name" value={details.Name} onChange={(e) => setDetails({ ...details, Name: e.target.value })} />
<input type="text" placeholder="Enter number" value={details.Number} onChange={(e) => setDetails({ ...details, Number: e.target.value })} />
I dont know how to write access the subjects respectively
Assuming you only want to change the first object of the array in this case, it would look like this:
<input
type="text"
placeholder="Enter subject1"
value={details.subject[0].subject1}
onChange={(e) =>
setDetails((curr) => ({
...curr,
subject: [
{ ...curr.subject[0], subject1: e.target.value },
...curr.subject,
],
}))
}
/>
<input
type="text"
placeholder="Enter subject2"
value={details.subject[0].subject2}
onChange={(e) =>
setDetails((curr) => ({
...curr,
subject: [
{ ...curr.subject[0], subject2: e.target.value },
...curr.subject,
],
}))
}
/>
Please note that the
curr
callback is to use the current state. This is better than using thedetails
state, since it is set async.