'How to add dynamically created input field values to a use state array?
Continuing troubleshooting from Adding data to array using UseState onChange
Hi, i am trying to make a button, that adds a new input field, then, when i click another submit button, i want to take the value from all the input fields and add them to an array in a useState.
I did first try to do it like in the linked post, (adding value of the input field onBlur), the issue with this, is that if the user goes back and changes the value in an input field, the old value will still be there. I need to define that the user is done typing when he clicks the submit button.
So now i am thinking i will need to make a function which runs with another submit button, but how will i then get the values of the dynamically created input fields? I understand how to get value from an input using a state with onChange, but it might be 1 inputfield, or it might be 100.
How could i dynamically add a new inputfield, save the value of all the inputfields created, in an state array, when i click the submit button?
relevant Code so far
const [subjectFieldsCounter, setSubjectFieldsCounter] = useState([])
const [subject, setSubject] = useState([]);
function addSubjectField(){
setSubjectFieldsCounter(oldArray => [...oldArray, "randomValueToIncreaseArraySize"])
}
<div>
<h4>Emne:</h4>
<input type="text" placeholder={"Eks. 'Random subject'"} onBlur={(e) => setSubject(oldArray => [...oldArray, e.target.value])}/>
<div><button onClick={addSubjectField}>+</button></div>
{subjectFieldsCounter.map((field) => (
<h2>
<input type="text" placeholder={"Eks. 'Random subject'"} onBlur={(e) => setSubject(oldArray => [...oldArray, e.target.value])}/>
</h2>
))}
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|