I have couple of input fields and submit button - each time the values are written to inputs and are submitted only one of the input values will display randomly.
Example:
Instead of outputting all the values I need to print only one - randomly - and each time I will click on the submit another random value from input will appear. For that I guess I need to save somehow the values, so after each submit, the form will not reload empty.
This is how I handle it now:
const [values, setValues] = useState([]);
const addValue = (input1, input2, input3, input4) => {
setValues([...values, {input1, input2, input3, input4 }])
}
const [input1, setInput1] = useState('');
const [input2, setInput2] = useState('');
const [input3, setInput3] = useState('');
const [input4, setInput4] = useState('');
const handleSubmit = (e) => {
e.predeventDefault()
addValue(input1);
setInput1('');
addValue(input2);
setInput2('');
addValue(input3);
setInput3('');
addValue(input4);
setInput4('');
}
And my view:
{values.map(value => {
return( <li key={value.input1}></li>)
})}
<form onSubmit={handleSubmit}>
<input type="text" value={input1} onChange={(e) => setInput1(e.target.value )}/>
// the same repeated with input2, input3,....
My question is, how can I handle my solution ? I am new to react and I am not aware of the best ways how to handle it.