Reactively adding to an array of objects in React
Let's now examine the reactivity of an array of objects. In this case, we will have to make any changes by accessing elements by id, which are stored inside the objects themselves.
Let's try it. Let's say we have the following array of objects:
jsxconst initNotes = [
{
id: 'GYi9G_uC4gBF1e2SixDvu',
prop1: 'value11',
prop2: 'value12',
prop3: 'value13',
},
{
id: 'IWSpfBPSV3SXgRF87uO74',
prop1: 'value21',
prop2: 'value22',
prop3: 'value23',
},
{
id: 'JAmjRlfQT8rLTm5tG2m1L',
prop1: 'value31',
prop2: 'value32',
prop3: 'value33',
},
];
Let's output each element of our array in a separate li tag:
jsxfunction 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>
</li>;
});
return <div>
<ul>
{result}
</ul>
</div>;
}
Задание 1
Make a button that, when clicked, will add a new element to the end of the array, thereby adding a new li to the end of the ul tag.
Задание 2
Make three inputs and a button. When the button is clicked, create a new li from the input data at the end of the ul tag.