Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How unique should a React component Key be?

Tags:

This is a quick one: what is the scope in which the children keys have to be unique? Is this just the parent component or the whole app?

If the latter is true, does it mean react diff algorithm will preserve an element when its moved across parent components?

like image 335
konrad Avatar asked Oct 30 '15 05:10

konrad


People also ask

Do React keys need to be unique?

Keys Must Only Be Unique Among Siblings Keys serve as a hint to React but they don't get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name: const content = posts.

Do React components have a unique id?

Both react-async and react-multiplayer need components to have unique identifiers.

How do I pass a unique key in React?

Use the video id (arqTu9Ay4Ig) as a unique ID. That way, if that ID doesn't change, the component will stay the same, but if it does, React will recognize that it's a new Video and change it accordingly.

Why each child in a list should have a unique key prop?

⚠️ Warning: Each child in a list should have a unique “key” prop. This is because React uses a unique “key” prop on each child of the list to create a relationship between the component and the DOM. This is to ensure that react re-renders the child correctly next time.


2 Answers

Unique within its siblings, so the level directly under its parent. The children of the parent component however can use the same key again, because finally, react will compose the complete key out of the key of the current component and all of its ancestors. The example below only contains auto-generated keys, but if you provide your own key, it will be used instead.

React ID's

You can see the composed ID's in Chrome developer tools (tab Elements).

like image 154
Björn Boxstart Avatar answered Sep 18 '22 06:09

Björn Boxstart


Yes, looks like it...if you re-parent it, it'll give a different reactid (eg. http://webcloud.se/react-sortable/nested.html )

and will unmount/re-mount again. ...

http://jsfiddle.net/46x0j6uq/1/

,componentWillUnmount: function() {  //console.log("unmounted:", this.props);  clearInterval(this.state.intervalId);  clearTimeout(this.state.timeoutId); } ,componentDidMount: function(){   // console.log("mounted:", this.props);   this.state.intervalId = setInterval(this.incrementCount, 1000);  this.state.timeoutId = setTimeout(this.setColorToBlack, 300); } 

So, better not to store state in the view component itself, since it might reset itself. The above fiddle is just a demo to prove a point.

Other related links: Using keys to identify nested components in React.js

I did wish React had something to consider scoped/nested key states beyond the same level, but i guess the performance of unmounting/re-mounting again should hopefully not be too detrimental.

like image 42
Glenn Ko Avatar answered Sep 21 '22 06:09

Glenn Ko