Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between key={`note${note.id}`}> and key={note.id} in React JSX?

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.

like image 486
user3839821 Avatar asked Nov 28 '25 14:11

user3839821


2 Answers

<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>
like image 134
Alexandre Kirszenberg Avatar answered Nov 30 '25 06:11

Alexandre Kirszenberg


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.

like image 27
psigns Avatar answered Nov 30 '25 05:11

psigns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!