Preserving and Resetting State·续2
function Field({ label }) { const [text, setText] = useState(''); return ( <label> {label}:{' '} <input type="text" value={text} placeholder={label} onChange={e => setText(e.target.value)} /> </label> ); }
```css
label { display: block; margin: 10px 0; }
Give a key to both <Field> components in both if and else branches. This tells React how to "match up" the correct state for either <Field> even if their order within the parent changes:
```js src/App.js import { useState } from 'react';
export default function App() { const [reverse, setReverse] = useState(false); let checkbox = ( <label> <input type="checkbox" checked={reverse} onChange={e => setReverse(e.target.checked)} /> Reverse order </label> ); if (reverse) { return ( <> <Field key="lastName" label="Last name" /> <Field key="firstName" label="First name" /> {checkbox} </> ); } else { return ( <> <Field key="firstName" label="First name" /> <Field key="lastName" label="Last name" /> {checkbox} </> ); } }
function Field({ label }) { const [text, setText] = useState(''); return ( <label> {label}:{' '} <input type="text" value={text} placeholder={label} onChange={e => setText(e.target.value)} /> </label> ); }
```css
label { display: block; margin: 10px 0; }
Reset a detail form
This is an editable contact list. You can edit the selected contact's details and then either press "Save" to update it, or "Reset" to undo your changes.
When you select a different contact (for example, Alice), the state updates but the form keeps showing the previous contact's details. Fix it so that the form gets reset when the selected contact changes.
```js src/App.js import { useState } from 'react'; import ContactList from './ContactList.js'; import EditContact from './EditContact.js';
export default function ContactManager() { const [ contacts, setContacts ] = useState(initialContacts); const [ selectedId, setSelectedId ] = useState(0); const selectedContact = contacts.find(c => c.id === selectedId );
function handleSave(updatedData) { const nextContacts = contacts.map(c => { if (c.id === updatedData.id) { return updatedData; } else { return c; } }); setContacts(nextContacts); }
return ( <div> <ContactList contacts={contacts} selectedId={selectedId} onSelect={id => setSelectedId(id)} /> <hr /> <EditContact initialData={selectedContact} onSave={handleSave} /> </div> ) }
const initialContacts = [ { id: 0, name: 'Taylor', email: 'taylor@mail.com' }, { id: 1, name: 'Alice', email: 'alice@mail.com' }, { id: 2, name: 'Bob', email: 'bob@mail.com' } ];
```js src/ContactList.js
export default function ContactList({
contacts,
selectedId,
onSelect
}) {
return (
<section>
<ul>
{contacts.map(contact =>
<li key={contact.id}>
<button onClick={() => {
onSelect(contact.id);
}}>
{contact.id === selectedId ?
<b>{contact.name}</b> :
contact.name
}
</button>
</li>
)}
</ul>
</section>
);
}
```js src/EditContact.js import { useState } from 'react';
export default function EditContact({ initialData, onSave }) { const [name, setName] = useState(initialData.name); const [email, setEmail] = useState(initialData.email); return ( <section> <label> Name:{' '} <input type="text" value={name} onChange={e => setName(e.target.value)} /> </label> <label> Email:{' '} <input type="email" value={email} onChange={e => setEmail(e.target.value)} /> </label> <button onClick={() => { const updatedData = { id: initialData.id, name: name, email: email }; onSave(updatedData); }}> Save </button> <button onClick={() => { setName(initialData.name); setEmail(initialData.email); }}> Reset </button> </section> ); }
```css
ul, li {
list-style: none;
margin: 0;
padding: 0;
}
li { display: inline-block; }
li button {
padding: 10px;
}
label {
display: block;
margin: 10px 0;
}
button {
margin-right: 10px;
margin-bottom: 10px;
}
Give key={selectedId} to the EditContact component. This way, switching between different contacts will reset the form:
```js src/App.js import { useState } from 'react'; import ContactList from './ContactList.js'; import EditContact from './EditContact.js';
export default function ContactManager() { const [ contacts, setContacts ] = useState(initialContacts); const [ selectedId, setSelectedId ] = useState(0); const selectedContact = contacts.find(c => c.id === selectedId );
function handleSave(updatedData) { const nextContacts = contacts.map(c => { if (c.id === updatedData.id) { return updatedData; } else { return c; } }); setContacts(nextContacts); }
return ( <div> <ContactList contacts={contacts} selectedId={selectedId} onSelect={id => setSelectedId(id)} /> <hr /> <EditContact key={selectedId} initialData={selectedContact} onSave={handleSave} /> </div> ) }
const initialContacts = [ { id: 0, name: 'Taylor', email: 'taylor@mail.com' }, { id: 1, name: 'Alice', email: 'alice@mail.com' }, { id: 2, name: 'Bob', email: 'bob@mail.com' } ];
```js src/ContactList.js
export default function ContactList({
contacts,
selectedId,
onSelect
}) {
return (
<section>
<ul>
{contacts.map(contact =>
<li key={contact.id}>
<button onClick={() => {
onSelect(contact.id);
}}>
{contact.id === selectedId ?
<b>{contact.name}</b> :
contact.name
}
</button>
</li>
)}
</ul>
</section>
);
}
```js src/EditContact.js import { useState } from 'react';
export default function EditContact({ initialData, onSave }) { const [name, setName] = useState(initialData.name); const [email, setEmail] = useState(initialData.email); return ( <section> <label> Name:{' '} <input type="text" value={name} onChange={e => setName(e.target.value)} /> </label> <label> Email:{' '} <input type="email" value={email} onChange={e => setEmail(e.target.value)} /> </label> <button onClick={() => { const updatedData = { id: initialData.id, name: name, email: email }; onSave(updatedData); }}> Save </button> <button onClick={() => { setName(initialData.name); setEmail(initialData.email); }}> Reset </button> </section> ); }
```css
ul, li {
list-style: none;
margin: 0;
padding: 0;
}
li { display: inline-block; }
li button {
padding: 10px;
}
label {
display: block;
margin: 10px 0;
}
button {
margin-right: 10px;
margin-bottom: 10px;
}
Clear an image while it's loading
When you press "Next", the browser starts loading the next image. However, because it's displayed in the same <img> tag, by default you would still see the previous image until the next one loads. This may be undesirable if it's important for the text to always match the image. Change it so that the moment you press "Next", the previous image immediately clears.
Is there a way to tell React to re-create the DOM instead of reusing it?
import { useState } from 'react';
export default function Gallery() {
const [index, setIndex] = useState(0);
const hasNext = index < images.length - 1;
function handleClick() {
if (hasNext) {
setIndex(index + 1);
} else {
setIndex(0);
}
}
let image = images[index];
return (
<>
<button onClick={handleClick}>
Next
</button>
<h3>
Image {index + 1} of {images.length}
</h3>
<img src={image.src} />
<p>
{image.place}
</p>
</>
);
}
let images = [{
place: 'Penang, Malaysia',
src: 'https://react.dev/images/docs/scientists/FJeJR8M.jpg'
}, {
place: 'Lisbon, Portugal',
src: 'https://react.dev/images/docs/scientists/dB2LRbj.jpg'
}, {
place: 'Bilbao, Spain',
src: 'https://react.dev/images/docs/scientists/z08o2TS.jpg'
}, {
place: 'Valparaíso, Chile',
src: 'https://react.dev/images/docs/scientists/Y3utgTi.jpg'
}, {
place: 'Schwyz, Switzerland',
src: 'https://react.dev/images/docs/scientists/JBbMpWY.jpg'
}, {
place: 'Prague, Czechia',
src: 'https://react.dev/images/docs/scientists/QwUKKmF.jpg'
}, {
place: 'Ljubljana, Slovenia',
src: 'https://react.dev/images/docs/scientists/3aIiwfm.jpg'
}];
img { width: 150px; height: 150px; }
You can provide a key to the <img> tag. When that key changes, React will re-create the <img> DOM node from scratch. This causes a brief flash when each image loads, so it's not something you'd want to do for every image in your app. But it makes sense if you want to ensure the image always matches the text.
import { useState } from 'react';
export default function Gallery() {
const [index, setIndex] = useState(0);
const hasNext = index < images.length - 1;
function handleClick() {
if (hasNext) {
setIndex(index + 1);
} else {
setIndex(0);
}
}
let image = images[index];
return (
<>
<button onClick={handleClick}>
Next
</button>
<h3>
Image {index + 1} of {images.length}
</h3>
<img key={image.src} src={image.src} />
<p>
{image.place}
</p>
</>
);
}
let images = [{
place: 'Penang, Malaysia',
src: 'https://react.dev/images/docs/scientists/FJeJR8M.jpg'
}, {
place: 'Lisbon, Portugal',
src: 'https://react.dev/images/docs/scientists/dB2LRbj.jpg'
}, {
place: 'Bilbao, Spain',
src: 'https://react.dev/images/docs/scientists/z08o2TS.jpg'
}, {
place: 'Valparaíso, Chile',
src: 'https://react.dev/images/docs/scientists/Y3utgTi.jpg'
}, {
place: 'Schwyz, Switzerland',
src: 'https://react.dev/images/docs/scientists/JBbMpWY.jpg'
}, {
place: 'Prague, Czechia',
src: 'https://react.dev/images/docs/scientists/QwUKKmF.jpg'
}, {
place: 'Ljubljana, Slovenia',
src: 'https://react.dev/images/docs/scientists/3aIiwfm.jpg'
}];
img { width: 150px; height: 150px; }
Fix misplaced state in the list
In this list, each Contact has state that determines whether "Show email" has been pressed for it. Press "Show email" for Alice, and then tick the "Show in reverse order" checkbox. You will notice that it's Taylor's email that is expanded now, but Alice's--which has moved to the bottom--appears collapsed.
Fix it so that the expanded state is associated with each contact, regardless of the chosen ordering.
```js src/App.js import { useState } from 'react'; import Contact from './Contact.js';
export default function ContactList() { const [reverse, setReverse] = useState(false);
const displayedContacts = [...contacts]; if (reverse) { displayedContacts.reverse(); }
return ( <> <label> <input type="checkbox" checked={reverse} onChange={e => { setReverse(e.target.checked) }} />{' '} Show in reverse order </label> <ul> {displayedContacts.map((contact, i) => <li key={i}> <Contact contact={contact} /> </li> )} </ul> </> ); }
const contacts = [ { id: 0, name: 'Alice', email: 'alice@mail.com' }, { id: 1, name: 'Bob', email: 'bob@mail.com' }, { id: 2, name: 'Taylor', email: 'taylor@mail.com' } ];
```js src/Contact.js
import { useState } from 'react';
export default function Contact({ contact }) {
const [expanded, setExpanded] = useState(false);
return (
<>
<p><b>{contact.name}</b></p>
{expanded &&
<p><i>{contact.email}</i></p>
}
<button onClick={() => {
setExpanded(!expanded);
}}>
{expanded ? 'Hide' : 'Show'} email
</button>
</>
);
}
ul, li {
list-style: none;
margin: 0;
padding: 0;
}
li {
margin-bottom: 20px;
}
label {
display: block;
margin: 10px 0;
}
button {
margin-right: 10px;
margin-bottom: 10px;
}
The problem is that this example was using index as a key:
{displayedContacts.map((contact, i) =>
<li key={i}>
However, you want the state to be associated with each particular contact.
Using the contact ID as a key instead fixes the issue:
```js src/App.js import { useState } from 'react'; import Contact from './Contact.js';
export default function ContactList() { const [reverse, setReverse] = useState(false);
const displayedContacts = [...contacts]; if (reverse) { displayedContacts.reverse(); }
return ( <> <label> <input type="checkbox" checked={reverse} onChange={e => { setReverse(e.target.checked) }} />{' '} Show in reverse order </label> <ul> {displayedContacts.map(contact => <li key={contact.id}> <Contact contact={contact} /> </li> )} </ul> </> ); }
const contacts = [ { id: 0, name: 'Alice', email: 'alice@mail.com' }, { id: 1, name: 'Bob', email: 'bob@mail.com' }, { id: 2, name: 'Taylor', email: 'taylor@mail.com' } ];
```js src/Contact.js
import { useState } from 'react';
export default function Contact({ contact }) {
const [expanded, setExpanded] = useState(false);
return (
<>
<p><b>{contact.name}</b></p>
{expanded &&
<p><i>{contact.email}</i></p>
}
<button onClick={() => {
setExpanded(!expanded);
}}>
{expanded ? 'Hide' : 'Show'} email
</button>
</>
);
}
ul, li {
list-style: none;
margin: 0;
padding: 0;
}
li {
margin-bottom: 20px;
}
label {
display: block;
margin: 10px 0;
}
button {
margin-right: 10px;
margin-bottom: 10px;
}
State is associated with the tree position. A key lets you specify a named position instead of relying on order.
