React elements

How can I generate different keys for React elements?

The most fundamental ideas in React are lists and keys. For those just starting to build their first application utilizing the React framework, it can be the first terrifying one. Even scarier, lists are a need because practically every application has repetitive information of some kind.

But it’s actually quite simple. It merely needs an explanation.

Because of this, I choose to explain lists, how to create a list in JSX, what keys are, and how to correct one of the most typical problems related to lists and keys that you will frequently encounter in your console in this article.

const tasks = [
  {id: "1", salary: "10,000", status: "pending"},
  {id: "3", salary: "20,000", status: "Done"},
]

const tasksList = tasks.map(task => {
  return (
  <p key={task.id}>{task.salary} - {task.status}</p>
  )
});

I identified my list item in the code above by using the ID of each task. In this instance, it is already a string, but if it weren’t, we would need to use the.toString() method to convert it.

However, it is also possible that you lack an ID or another usable unique value. Then, there is a different approach that enables the use of index.

const tasks = [
  {salary: "10,000", status: "pending"},
  {salary: "20,000", status: "Done"},
]

const tasksList = tasks.map((task, index) => {
  return (
  <p key={index}>{task.salary} - {task.status}</p>
  )
});

It is technically possible, and if you don’t pass the key, React will even do it by default, but it’s not a recommended option, especially if you want to edit the elements, like changing their position.

Given that the key is the sole thing that enables React to recognize an element in the DOM, if an element is added or removed, but the key remains the same, React might not recognize that the component has truly changed.

You should avoid using index in the key because it could cause problems, crash the program, or display incorrect data.

You must satisfy all three of the following requirements before you may use index as a key in your list without feeling guilty:

  • Never do you sort or filter the list.
  • You never alter or calculate the list or its items.
  • The list’s items lack identifiers.

There is one more thing that is required when making an element list in the manner you can see above, and that is a key.

It is technically possible, and if you don’t pass the key, React will even do it by default, but it’s not a recommended option, especially if you want to edit the elements, like changing their position.

Given that the key is the sole thing that enables React to recognise an element in the DOM, if an element is added or removed but the key remains the same, React might not recognise that the component has truly changed.

You should avoid using index in the key because it could cause problems, crash the programme, or display incorrect data.

You must include the special attribute key in the element, and it must be a string. Each list’s key should be distinct, thus you shouldn’t use values that could be the same as the key. In other words, keys must be exclusive to the siblings and not to the entire world.

For instance, in our case, you shouldn’t use status or text as a key.

Key functions as a kind of element ID that aids React in determining which element was modified, added, or removed.

It is the best practice to choose a value that serves as a special identifier for each item in the array; frequently, this is the ID.

var lists = this.state.lists.map(function(list, index) {
        return(
            <div key={index}>
                <div key={list.name} id={list.name}>
                    <h2 key={"header"+list.name}>{list.name}</h2>
                    <ListForm update={lst.updateSaved} name={list.name}/>
                </div>
            </div>
        )
});

Read this anywhere you’re looping over data. If you’re using this.state.lists.map, you can also supply the callback a second parameter, function(list, index), which will be the index value and be different for each item in the array.

After that, you can apply it as

var lists = this.state.lists.map(function(list, index) {
        return(
            <div key={index}>
                <div key={list.name} id={list.name}>
                    <h2 key={"header"+list.name}>{list.name}</h2>
                    <ListForm update={lst.updateSaved} name={list.name}/>
                </div>
            </div>
        )
});


How to generate unique keys React?

Let’s say you really need to utilize a different value than the index, but the data you are utilizing lacks unique values like ids or any other identifier. There are at least two ways to do it in such instance.

1. Create the key on your own.

You may write a straightforward Javascript function to produce a random integer or string. You can also use a new date (). The Javascript getTime() method can generate a random number, prefix it with any prefix, and use that number as your key.

2. Create the key on your own.

For creating unique keys for React lists, there are a couple ready-made solutions. Shortid and its generate() method is the one I use most frequently. Uuid and uniqid are the other ones that are suggested. They are all fairly easy to install and utilize.

conclusion:

I described how to create a list in React JSX, what keys are, and the importance of including them.Additionally, you learned how to create unique IDs and why key uniqueness matters in specific circumstances. I hope this guide will be helpful to you, especially if you are new to front-end programming or ReactJS.

Leave a Comment

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

Let's Get in Touch

Read our customer feedback

Please fill in the form below.


    To top