I've got a form component, where you can add an input on click of the button, creating a new team, where you can add players for.
The problem is, that if you fill in a value, all inputs will be filled with that value, because it is using the same state. My guess is to make a new state value for each new team (something like 'input' + index, which would result in states like input0, input1, input2, etc).
Though I can't implement this using React Hooks as you have to declare your state at first, and assign a set function to it.
Any thought on how I can implement this behaviour?
Here's just one solution that's pretty straightforward, keeping track of values in an array, just to illustrate that hooks don't make anything more difficult:
function App() {
let [inputs, setInputs] = useState([""]);
return (
<div className="App">
<button onClick={() => setInputs(inputs.concat(""))}>Add input</button>
<form>
{inputs.map((value, i) => (
<div key={i}>
<label>Input {i + 1}</label>
<input
value={value}
onChange={e =>
setInputs(
inputs.map((value, j) => {
if (i === j) value = e.target.value;
return value;
})
)
}
/>
</div>
))}
</form>
</div>
);
}
codesandbox
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With