Binding Inputs to an Array in React
Let the state notes
store an array:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
return <div>
</div>;
}
Let us also have an auxiliary function that finds the sum of the elements of an array:
function getSum(arr) {
let sum = 0;
for (const elem of arr) {
sum += +elem;
}
return sum;
}
function App() {
...
}
Let's find and print the sum of the elements of our array from the state using our helper function:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
return <div>
{getSum(notes)}
</div>;
}
Let's now make three inputs and write one of the array elements into value
of each input:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
return <div>
<input value={notes[0]} />
<input value={notes[1]} />
<input value={notes[2]} />
{getSum(notes)}
</div>;
}
Let's now add the onChange
event to our inputs. At the same time, let's make one common handler function for this event:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
function changeHandler(index, event) {
// general handler function
}
return <div>
<input value={notes[0]} onChange={event => changeHandler(0, event)} />
<input value={notes[1]} onChange={event => changeHandler(1, event)} />
<input value={notes[2]} onChange={event => changeHandler(2, event)} />
{getSum(notes)}
</div>;
}
As you can see, the changeHandler
function takes as its first parameter the number of the array element that edits the given input.
Using this number we can replace the array element with the contents of the input.
Let's do this:
function changeHandler(index, event) {
setNotes([...notes.slice(0, index), event.target.value, ...notes.slice(index + 1)]);
}
Now it will be possible to edit any input, and the array will be changed reactively and, accordingly, the sum of its elements will be recalculated.
Let's put all our code together:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
function changeHandler(index, event) {
setNotes([...notes.slice(0, index), event.target.value, ...notes.slice(index + 1)]);
}
return <div>
<input value={notes[0]} onChange={event => changeHandler(0, event)} />
<input value={notes[1]} onChange={event => changeHandler(1, event)} />
<input value={notes[2]} onChange={event => changeHandler(2, event)} />
{getSum(notes)}
</div>;
}
You can make it so that the inputs are generated in a loop:
function App() {
const [notes, setNotes] = useState([1, 2, 3]);
function changeHandler(index, event) {
setNotes([...notes.slice(0, index), event.target.value, ...notes.slice(index + 1)]);
}
const result = notes.map((note, index) => {
return <input
key={index}
value={note}
onChange={event => changeHandler(index, event)}
/>;
});
return <div>
{result}
{getSum(notes)}
</div>;
}
The following array is given:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Display the arithmetic mean of the elements of this array. In the loop, make inputs for editing the elements.