Reactive operations on arrays of objects in React
Now let's learn how to do reactive operations on arrays of objects. In this case, we need to pass to the function id
of the array element we are going to do something with:
function App() {
const [notes, setNotes] = useState(initNotes);
const result = notes.map(note => {
return <li key={note.id}>
<span>{note.prop1}</span>
<span>{note.prop2}</span>
<span>{note.prop3}</span>
<button onClick={() => doSmth(note.id)}>
btn
</button>
</li>;
});
return <div>
<ul>
{result}
</ul>
</div>;
}
In order to do anything with an element, we first have to find it by looping through the entire array:
function App() {
...
function doSmth(id) {
setNotes(notes.map(note => {
if (note.id === id) {
// we do something with the element
}
return note;
}));
}
}
Let's change the texts of the found object as an example:
function App() {
...
function doSmth(id) {
setNotes(notes.map(note => {
if (note.id === id) {
note.prop1 += '!';
note.prop2 += '!';
note.prop2 += '!';
return note;
}
return note;
}));
}
}
At the end of each li
make a button that, when clicked, will remove this li
from the list.
Three inputs are given. At the end of each li
, make a button that, when pressed, will send the data of the object of this li
to the corresponding inputs.
Modify the previous task so that there is a button next to the inputs, which, when clicked, will send the input data to the corresponding li
.