I have three number inputs:
<input type='number'>number1</input>
<input type='number'>number2</input>
<input type='number'>number3</input>
I wish to store the state as an array of objects so it looks like the following after a user has entered three numbers:
[{ par: number1 }, { par: number2 }, { par: number3 }]
I also want the user to be able to edit a number so if the user changes his/her mind, they can simply edit an existing number which will edit the corresponding value in the state.
My understanding is that when you want to add elements to the state you use the spread operator and when you want to edit elements in the state you use the map function. I know how to implement each way of updating state but I am not sure how to determine on the change of an input, if the state should be added to or edited. I guess I need a way of determining that on each input change? but I am not sure how to do that.
CodePudding user response:
If you are just asking how to implement an onChange
handler for three inputs that update one of three elements in an array then I suggest passing an index as well as the value you want to update.
An example:
const [state, setState] = React.useState([
{ par: 0 },
{ par: 0 },
{ par: 0 }
]);
// Curried function to close over index in callback scope
const changeHandler = index => e => {
const { value } = e.target;
setState(state => state.map(
(current, i) => i === index ? { par: Number(value) } : current
);
};
return (
<>
{state.map(({ par }, i) => (
<label key={i}>
number {i 1}
<input
type="number"
value={par}
onChange={changeHandler(i)}
/>
</label>
))}
</>
);
CodePudding user response:
Here is the sample code of the above problem. This code will help you to solve your issue.
import React, {useState} from "react";
import "./App.css";
function App() {
const [data, setData] = useState([
{par: 0}, {par: 0}, {par: 0}
])
const onChange = (elem, val) => {
const tempData = [...data]
tempData[elem] = {
par: Number.parseInt(val)
}
setData(tempData)
}
return (
<div className="App">
<div>Number 1
<input type='number'
onChange={(e) => onChange(0, e.target.value)}/>
</div>
<div>Number 2
<input type='number'
onChange={(e) => onChange(1, e.target.value)}/>
</div>
<div>Number 3
<input type='number'
onChange={(e) => onChange(2, e.target.value)}/>
</div>
</div>
);
}
export default App;