Importance of React Keys
Introduction
The context
function ChatLobby() {
const [selectedUser, setSelectedUser] = useState("Timothee");
return (
<div>
<header>
<button onClick={() => setSelectedUser("Timothee")}>
Timothee
</button>
<button onClick={() => setSelectedUser("Adam")} >
Adam
</button>
</header>
<section>
{selectedUser === "Timothee"
? <Chat with="Timothee" />
: <Chat with="Adam" />}
</section>
</div>
)
}
function Chat(props) {
const [text, setText] = useState("");
return (
<div>
<h4>Write a message to <span>{props.with}</span></h4>
<input value={text} onChange={e => setText(e.target.value)} />
<button>Send</button>
</div>
)
}Let's see what's going on
Can you spot the problem?
How to avoid the problem?
Use key prop
Split the condition
Conclusion
Last updated