How and why to use keys in React

Other topics

Remarks:

For more information, visit this link to read how to use keys: https://facebook.github.io/react/docs/lists-and-keys.html

And visit this link to read why it is recommended to use keys: https://facebook.github.io/react/docs/reconciliation.html#recursing-on-children

Basic Example

For a class-less React component:

function SomeComponent(props){

    const ITEMS = ['cat', 'dog', 'rat']
    function getItemsList(){
        return ITEMS.map(item => <li key={item}>{item}</i>);
    }
    
    return (
        <ul>
            {getItemsList()}
        </ul>
    );
}

For this example, the above component resolves to:

<ul>
    <li key='cat'>cat</li>
    <li key='dog'>dog</li>
    <li key='rat'>rat</li>
<ul>

Contributors

Topic Id: 9665

Example Ids: 29827

This site is not affiliated with any of the contributors.