⊗jsrtPmCpEGS 89 of 112 menu

Editing State in a Grandchild Component in React

Let's consider the component Product that we obtained in the previous lesson:

function Product({ id, name, cost, isEdit, toggleMode, editProd }) { return <div> name: { isEdit ? <input value={name} onChange={event => editProd(id, 'name', event)} /> : <span>{name}</span> } cost: { isEdit ? <input value={cost} onChange={event => editProd(id, 'cost', event)} /> : <span>{cost}</span> } <button onClick={() => toggleMode(id)}> {isEdit ? 'save': 'edit'} </button> </div>; }

It is easy to notice that the code for the product name and for the product price is almost duplicated. Let's move this code to a separate component ProductField:

function ProductField({ id, text, type, isEdit, editProd }) { return isEdit ? <input value={text} onChange={event => editProd(id, type, event)} /> : <span>{text}</span> ; }

Let's make changes to the Product component:

function Product({ id, name, cost, isEdit, toggleMode, editProd }) { return <div> name: <ProductField id={id} text={name} type="name" isEdit={isEdit} editProd={editProd} />, cost: <ProductField id={id} text={cost} type="cost" isEdit={isEdit} editProd={editProd} /> <button onClick={() => toggleMode(id)}> {isEdit ? 'save': 'edit'} </button> </div>; }

Do the same with the User component you created in the previous lessons.

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