React Keys

React keys are useful when working with dynamically created components or when your lists are altered by the users. Setting the key value will keep your components uniquely identified after the change.

import React from 'react';

class App extends React.Component {
   constructor() {
      super();
        
      this.state = {
         users:[
            {
               name: 'Folau',
               id: 1
            },
            {
               name: 'Lisa',
               id: 2
            }
         ]
      }
   }
   render() {
      return (
         <div>
            <div>
               {this.state.data.map((user, i) => 
                <h4>My name is {user.name}<h4/>
               )}
            </div>
         </div>
      );
   }
}

It’s strongly recommended that you assign proper keys whenever you build dynamic lists. If you don’t have an appropriate key, you may want to consider restructuring your data so that you do.

If no key is specified, React will present a warning and use the array index as a key by default. Using the array index as a key is problematic when trying to re-order a list’s items or inserting/removing list items. Explicitly passing key={i} silences the warning but has the same problems as array indices and is not recommended in most cases.

Keys do not need to be globally unique; they only need to be unique between components and their siblings.

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *