I am following a React tutorial and the author has some code like:
<li key={`note${note.id}`}>
<Note task={note.task} />
</li>
however, the same code also works if you simply do:
<li className="note" key={note.id}>
<Note task={note.task}/>
</li>
what is the purpose of the `note$ before the actual note.id in the first example? Both work, only curious why this is there.
<li key={`note${note.id}`}> is equivalent to <li key={"note" + note.id}>.
In React, the key prop is used to reconcile elements between renders. All children elements of a DOM component must have unique keys. See Reconciliation.
Assigning the value note.id to the key prop of your <li> elements ensures that all of them have different and unique keys. Prefixing it with "note" ensures that there is no overlap if your parent element also contains other elements.
Here is an example where prefixing the keys is mandatory, since ids can be shared between notes and drafts.
var notes = [
{ id: 0, message: 'foo' },
{ id: 1, message: 'bar' },
];
var drafts = [
{ id: 0, message: 'foo' },
{ id: 1, message: 'bar' },
];
var children = notes.map(function(note) {
return <li key={`note${note.id}`}><Note /></li>;
}).concat(drafts.map(function(draft) {
return <li key={`draft${draft.id}`}><Draft /></li>;
}));
return <ul>{children}</ul>
The two examples are setting different keys.
Assume the note object has an id of 1.
The top example key={'notes${note.id}'}> is setting the key attribute equal to 'note1'.
The bottom example key={note.id} is setting the key equal to '1'.
They will both work because the key attribute is just used to uniquely identify children of a component. The top one key="note1" is probably better, just because it is more descriptive and specific and readable. You could imagine a React component that has more than one type of child, and their keys could clash if they were both given simple numeric keys.
This
`${variableName}`
syntax is the new ES6 Javascript string formatting syntax, similar to string interpolation in python or ruby. See the docs here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With