⊗jsrtPmDtOAA 75 of 112 menu

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:

const 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:

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> </li>; }); return <div> <ul> {result} </ul> </div>; }

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.

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.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline