20210827 - Question about Key Attribute in React
2021-08-27 00:00:00
# React
# Solved
Reference
Index as a key is an anti-pattern
Index as a key is an anti-pattern
Examples
Example 1
WRONG:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import React from "react";
const Note = ({note}) => { return ( <li key={note.id}>{note.content}</li> ) }
const App = ({ notes }) => { return ( <div> <h1>Notes</h1> <ul> {notes.map(note => <Note note={note}/> )} </ul> </div> ) }
export default App;
|
Error I got:
index.js:1 Warning: Each child in a list should have a unique “key” prop.
Check the render method of App
. See https://reactjs.org/link/warning-keys for more information.
at Note (http://localhost:3000/static/js/main.chunk.js:24:3)
at App (http://localhost:3000/static/js/main.chunk.js:38:3)
CORRECT:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import React from "react";
const Note = ({note}) => { return ( <li>{note.content}</li> ) }
const App = ({ notes }) => { return ( <div> <h1>Notes</h1> <ul> {notes.map(note => <Note key={note.id} note={note}/> )} </ul> </div> ) }
export default App;
|