190

I am making a React app that allows you to make a list and save it, but React has been giving me a warning that my elements don't have a unique key prop (elements List/ListForm). How should I create a unique key prop for user created elements? Below is my React code

var TitleForm = React.createClass({
    handleSubmit: function(e) {
        e.preventDefault();
        var listName = {'name':this.refs.listName.value};
        this.props.handleCreate(listName);
        this.refs.listName.value = "";
    },
    render: function() {
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    <input className='form-control list-input' type='text' ref='listName' placeholder="List Name"/>
                    <br/>
                    <button className="btn btn-primary" type="submit">Create</button>
                </form>
            </div>
        );
    }
});

var ListForm = React.createClass({
    getInitialState: function() {
        return {items:[{'name':'item1'}],itemCount:1};
    },
    handleSubmit: function(e) {
        e.preventDefault();
        var list = {'name': this.props.name, 'data':[]};
        var items = this.state.items;
        for (var i = 1; i < items.length; i++) {
            list.data.push(this.refs[items[i].name]);
        }
        this.props.update(list);
        $('#'+this.props.name).remove();
    }, 
    handleClick: function() {
        this.setState({
            items: this.state.items.concat({'name':'item'+this.state.itemCount+1}),
            itemCount: this.state.itemCount+1
        });
    },
    handleDelete: function() {
        this.setState({
            itemCount: this.state.itemCount-1
        });
    },
    render: function() {
        var listItems = this.state.items.map(function(item) {
            return (
                <div>
                    <input type="text" className="list-form" placeholder="List Item" ref={item.name}/>
                    <br/>
                </div>
            );
        });
        return (
            <div>
                <form onSubmit={this.handleSubmit} className="well list-form-container">
                    {listItems}
                    <br/>
                    <div onClick={this.handleClick} className="btn btn-primary list-button">Add</div>
                    <div onClick={this.handleDelete} className="btn btn-primary list-button">Delete</div>
                    <button type="submit" className="btn btn-primary list-button">Save</button>
                </form>
            </div>
        )
    }
});


var List = React.createClass({
    getInitialState: function() {
        return {lists:[], savedLists: []};
    },
    handleCreate: function(listName) {
        this.setState({
            lists: this.state.lists.concat(listName)
        });
    },
    updateSaved: function(list) {
        this.setState({
            savedLists: this.state.savedLists.concat(list)
        });
    },
    render: function() {
        var lst = this;
        var lists = this.state.lists.map(function(list) {
            return(
                <div>
                    <div key={list.name} id={list.name}>
                        <h2 key={"header"+list.name}>{list.name}</h2>
                        <ListForm update={lst.updateSaved} name={list.name}/>
                    </div>
                </div>
            )
        });
        var savedLists = this.state.savedLists.map(function(list) {
            var list_data = list.data;
            list_data.map(function(data) {
                return (
                    <li>{data}</li>
                )
            });
            return(
                <div>
                    <h2>{list.name}</h2>
                    <ul>
                        {list_data}
                    </ul>
                </div>
            )
        });
        var save_msg;
        if(savedLists.length == 0){
            save_msg = 'No Saved Lists';
        }else{
            save_msg = 'Saved Lists';
        }
        return (
            <div>
                <TitleForm handleCreate={this.handleCreate} />
                {lists}
                <h2>{save_msg}</h2>
                {savedLists}
            </div>
        )
    }
});

ReactDOM.render(<List/>,document.getElementById('app'));

My HTML:

<div class="container">
    <h1>Title</h1>
    <div id="app" class="center"></div>
</div>
6
  • 2
    You can use uuid npm package. npmjs.com/package/uuid Commented Nov 13, 2017 at 6:34
  • @RIYAJKHAN - If you use this package can you make one global version of const uuidv4 = require('uuid/v4'); or should you have one per component? Commented Jul 18, 2018 at 19:53
  • @chobo2 there is nothing like . global or local to component.You can import and use it Commented Jul 19, 2018 at 3:18
  • @RIYAJKHAN - I meant should I put it in it's own file and then export it into other components? But it sounds like there is no point doing that. Commented Jul 19, 2018 at 16:19
  • no need to export in other component,Just import in the component where you want to use it Commented Jul 19, 2018 at 17:06

21 Answers 21

115

It is important to remember that React expects STABLE keys, meaning you should assign the keys once and every item on your list should receive the same key every time, that way React can optimize around your data changes when it is reconciling the virtual DOM and decides which components need to re-render. So, if you are using UUID you need to do it at the data level, not at the UI level.

Also keep in mind you can use any string you want for the key, so you can often combine several fields into one unique ID, something like ${username}_${timestamp} can be a fine unique key for a line in a chat, for example.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for confirming this. I was doing key={uuid()} but noticed it changed all the keys after any action which pretty made all elements rerender.
Good point about the stable keys, which is not mentioned in other answers.
If you have the time and want to, please consider making an article or a self-answered question on stack about how to do it. Many people do it wrong, the accepted answer do it wrong. It would be very useful for the community
"So, if you are using UUID you need to do it at the data level, not at the UI level." How this translate in practice considering that those "data" can be comments in a blog, or as React comes from fb, simply comments. I now understand how sometimes even fb felt buggy and "lost" some comments. I mean what about when element are deleted, in such case also the id correleted should be removed and be sure not to be assigned to something else
@CarmineTambascia In most cases you can find a formula to use that would be unique and stable, in the worst niche case (supposed you have an array with long strings and that is all you have) you can use a hash function like this one here (stackoverflow.com/a/52171480/3052465) and produce a key from it, the important thing is that the key is stable.
|
114

There are many ways in which you can create unique keys, the simplest method is to use the index when iterating arrays.

Example

    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>
        )
    });

Wherever you're looping over data, here this.state.lists.map, you can pass second parameter function(list, index) to the callback as well and that will be its index value and it will be unique for all the items in the array.

And then you can use it like

<div key={index}>

You can do the same here as well

    var savedLists = this.state.savedLists.map(function(list, index) {
        var list_data = list.data;
        list_data.map(function(data, index) {
            return (
                <li key={index}>{data}</li>
            )
        });
        return(
            <div key={index}>
                <h2>{list.name}</h2>
                <ul>
                    {list_data}
                </ul>
            </div>
        )
    });

Edit

However, as pointed by the user Martin Dawson in the comment below, this is not always ideal.

So what's the solution then?

Many

  • You can create a function to generate unique keys/ids/numbers/strings and use that
  • You can make use of existing npm packages like uuid, uniqid, etc
  • You can also generate random number like new Date().getTime(); and prefix it with something from the item you're iterating to guarantee its uniqueness
  • Lastly, I recommend using the unique ID you get from the database, If you get it.

Example:

const generateKey = (pre) => {
    return `${ pre }_${ new Date().getTime() }`;
}

const savedLists = this.state.savedLists.map( list => {
    const list_data = list.data.map( data => <li key={ generateKey(data) }>{ data }</li> );
    return(
        <div key={ generateKey(list.name) }>
            <h2>{ list.name }</h2>
            <ul>
                { list_data }
            </ul>
        </div>
    )
});

13 Comments

This is fine if the elements do not get removed or added to them but if they do then you will have weird side-effects as React will associate the keys with wrong components
Using the index is an anti pattern. Just don't do it; there is going to be a time where it's going to go awry and tracking it down isn't going to be fun. Updated* Actually someone else pointed this out already @jayqui
Why you are generating unique id on every render? As it is pointed here - stackoverflow.com/a/53980483/4664866, react expect stable keys
dont use indexes and dont generate uuid on the fly - this is COMPLETELY WRONG. if you iterate over complex components - generating key on the fly will cause forced mount/unmount for component and all children. see in the comments above. the only correct thing in the answer - static uuids e.g. from database
Generating a random id doesn't solve the problem. We should not change the ids/keys between re-renders.
|
34

2024 Updated

Keys help React identify which items have changed/added/removed and should be given to the elements inside the array to give the elements a stable identity.

TL/DR: if your collection has a strong ID, use it; if not, you must choose between nanoid or product_type_${item.id} and with that in mind, there are three different strategies as described below:

  1. Static Elements (when you don't need to keep HTML state (focus, cursor position, etc)
  2. Editable and sortable elements
  3. Editable but not sortable elements

Important to Know: The React Team does not recommend using the useId Hook. Check the documentation here. Instead, they say: "Keys should be generated from your data".

  <div id={item.id} />

For static elements, nanoid() will do just fine.

As React Documentation explains, we need to give stable identity to the elements and because of that, carefully choose the strategy that best suits your needs:

STATIC ELEMENTS

As we can also see in React Documentation, using the index for keys "if the order of items may change. This can negatively impact performance and cause issues with component state" is not recommended.

I recommend using a package called **nanoid**for static elements like tables, lists, etc.

  yarn add nanoid
  // or 
  npm install nanoid

The command to generate a new ID is nanoid().

Example:

  import { nanoid } from 'nanoid';

  interface ICustomDropDownProps {
    collection?: [];
    value?: string;
    onSelectedValueChanged?: (event: string) => void;
  }

  export CustomDropDown = (props: ICustomDropDownProps): React.ReactNode => {    
    return (
      <select value={props.value} onChange={props.onSelectedValueChanged}>
        {(props.collection ?? []).map((items) => {
          return (
           <option value={item.value} key={nanoid()}>
             {item.text}
           </option>
          );
        })}
      </select>
    );
  };

IMPORTANT: As React Virtual DOM relies on the key, with nanoid(), every time the element is re-rendered, a new key will be created, and the element will lose its HTML state, like focus or cursor position. Consider this when deciding how the key will be generated, as the strategy above can be useful only when you are building elements that won't change their values, like lists or read-only fields.

EDITABLE (sortable) FIELDS

If the element is sortable and you have a unique ID of the item, combine it with some extra string (in case you need to have the same information twice on a page). This is the most recommended scenario.

Example:

  interface ICustomDropDownProps {
    collection?: [];
    collectionName: string;
    value?: string;
    onSelectedValueChanged?: (event: string) => void;
  }

  export CustomDropDown = (props: ICustomDropDownProps): React.ReactNode => {    
    return (
      <select value={props.value} onChange={props.onSelectedValueChanged}>
        {(props.collection ?? []).map((items) => {
          return (
           <option value={item.value} key={`${props.collectionName}_${item.id.toString()}`}>
             {item.text}
           </option>
          );
        })}
      </select>
    );
  };

EDITABLE (non-sortable) FIELDS (e.g. INPUT ELEMENTS)

As a last resort, for editable (but non-sortable) fields like input, you can use some of the indexes with some starting text, as the element key cannot be duplicated.

Example:

  interface ICustomDropDownProps {
    collection?: [];
    collectionName: string;
    value?: string;
    onSelectedValueChanged?: (event: string) => void;
  }

  export CustomDropDown = (props: ICustomDropDownProps): React.ReactNode => {    
    return (
      <select value={props.value} onChange={props.onSelectedValueChanged}>
        {(props.collection ?? []).map((items, index) => {
          return (
           <option value={item.value} key={`${props.collectionName}_${index.toString()}`}>
             {item.text}
           </option>
          );
        })}
      </select>
    );
  };

Happy coding!

11 Comments

index isn't an anti-pattern, it's a tool of last-resort and the default that react falls back to if you don't provide a key. it works for stable lists that are rendered, but otherwise not re-ordered or modified.
This example certainly works, but generating new IDs on every render is not ideal. It will cause all the child options to also get re-rendered. In the case of a complex component you'll lose performance. It's best to try to alter the original item data and append these generated keys such that they can be reused. This will prevent unnecessary renders.
You are right Diamond. Thank you for your extra info. Also, an disadvantage of using keys is that if you are editing a text input, for example, we will definitely lose the focus for the same reason you mentioned above.
"If the element is sortable and you have a unique ID of the item, combine it with some extra string (in case you need to have the same information twice in a page)" - why do you need that? Key must be unique only among its siblings. Check react documentation - reactjs.org/docs/lists-and-keys.html
Anyone in 2023 trying to use shortID, it is now deprecated - npmjs.com/package/shortid , instead use nanoID. Check documentation - github.com/ai/nanoid
|
18

Do not use this return `${ pre }_${ new Date().getTime()}`;. It's better to have the array index instead of that because, even though it's not ideal, that way you will at least get some consistency among the list components, with the new Date function you will get constant inconsistency. That means every new iteration of the function will lead to a new truly unique key.

The unique key doesn't mean that it needs to be globally unique, it means that it needs to be unique in the context of the component, so it doesn't run useless re-renders all the time. You won't feel the problem associated with new Date initially, but you will feel it, for example, if you need to get back to the already rendered list and React starts getting all confused because it doesn't know which component changed and which didn't, resulting in memory leaks, because, you guessed it, according to your Date key, every component changed.

Now to my answer. Let's say you are rendering a list of YouTube videos. 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.

It doesn't have to be that strict, the little more relaxed variant is to use the title, like Erez Hochman already pointed out, or a combination of the attributes of the component (title plus category), so you can tell React to check if they have changed or not.

edited some unimportant stuff

Comments

11

Let React Assign Keys To Children

You may leverage React.Children API:

const { Children } = React;

const DATA = [
  'foo',
  'bar',
  'baz',
];

const MyComponent = () => (
  <div>
    {Children.toArray(DATA.map(data => <p>{data}</p>))}
  </div>
);


ReactDOM.render(<MyComponent />,document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

4 Comments

It works like a charm! Thanks! But I don't know if there is any side effect problem or something, anyone?
Doesnt work. The child must have a key.
@VinaySharma, it doesn't work for instance with Deleting items, it's the same as using an index.
This doesn't work. The key property needs to be a stable identity (that is, won't ever change for each object), and Children.toArray does change key. If you have objects that can be reordered, it won't work, and you're in trouble.
8

To add the latest solution for 2021...

I found that the project nanoid provides unique string ids that can be used as key while also being fast and very small.

After installing using npm install nanoid, use as follows:

import { nanoid } from 'nanoid';

// Have the id associated with the data.
const todos = [{id: nanoid(), text: 'first todo'}];

// Then later, it can be rendered using a stable id as the key.
const todoItems = todos.map((todo) =>
  <li key={todo.id}>
    {todo.text}
  </li>
)

3 Comments

This doesn' solve the case when the element is been removed for some reason and then key assigned to something else
You wouldn't want to reuse a key if something is removed.
yes you are right, but though didn't meant that. It all depends on how then the deleting function is handled
3

Another option is weak-key: https://www.npmjs.com/package/weak-key

import weakKey from "weak-key";

const obj1 = {a : 42};
const obj2 = {b : 123};
const obj3 = {a : 42};

console.log(weakKey(obj1)); // 'weak-key-1'
console.log(weakKey(obj2)); // 'weak-key-2'
console.log(weakKey(obj3)); // 'weak-key-3'

console.log(weakKey(obj1)); // 'weak-key-1'

1 Comment

This is a good approach to the problem. I'm looking how to use sha1 + uuid5 together to create uuid-s from vararg input. That way the uuid remains same if the input does not change. And the component would get its key like so: sha1uuid('my-sub-entity', indexA, indexB).
1

In the event that your data does not contain a unique ID (i.e. a database ID), you need to create a unique ID at the data level before the UI logic, so that the ID is stable. Generating ID's inside the key attribute are unstable, they cause React to destroy/create that element on every render because you are telling the ID itself to be changed on every render - React sees the key is different by comparison.

This is how you might amend the data within a component to have a simple stable numerical ID - it would be more efficient to amend the data further/as far up the component tree as possible. Using useRef to hold a persistent value, which is incremented each time a new ID is required, and useMemo to store the resulting amended data which will persist so long as the data it is based off does not change.

If you require the ID to be globally unique across the application i.e. if there is logic elsewhere utilizing the ID, then an external UUID generating package should be used. For simple lists where you just require a stable, unique ID, then an incrementing numeral value will suffice.

function Component(props) {
  const { data } = props;
  const idRef = useRef(-1);

  function getId() {
    idRef.current += 1;
    return idRef.current;
  }

  const dataAmended = useMemo(() => {
    return data.map((item) => {
      return { ...item, id: getId() };
    });
  }, [data]);

  const listItems = dataAmended.map((item) => {
    return <li key={item.id}>{item.title}</li>;
  });

  return <ul>{listItems}</ul>;
}

Comments

0

For a simple array of text-strings; I'm trying one of the two ways:

1. encodeURI which is available on both; NodeJS and browser


const WithEncoder = () => {
  const getKey = useCallback((str, idx) => encodeURI(`${str},${idx}`), [])

  return (
    <div>
      {["foo", "bar"].map((str, idx) => (
        <div key={getKey(str, idx)}>{str}</div>
      ))}
    </div>
  )
}

2. window.btoa which is available only in browser.

const WithB2A = () => {
  const getKey = useCallback((str, idx) => window.btoa(`${str}-${idx}`), [])

  return (
    <div>
      {["foo", "bar"].map((str, idx) => (
        <div key={getKey(str, idx)}>{str}</div>
      ))}
    </div>
  )
}

1 Comment

Using indices in keys is not advisable according to react docs. "As a last resort, you can pass an item’s index in the array as a key. This can work well if the items are never reordered, but reorders will be slow." reactjs.org/docs/reconciliation.html#recursing-on-children
0

Depends on the situation, choose a uniqueId creator is ok when you just want render silly items, but if you render items like drag&drop etc and you haven't any uniqueId for each item, I recommend remap that data in your redux, mapper, wherever and add for each item an uniqueId (and not in the render like <Item key={...}) because React couldn't perform any check between renders (and with that all the benefits).

With that remapped that you can use that new Id in your Component.

Comments

0

Here is what I have done, it works for reordering, adding, editing and deleting. Once set the key is not changed, so no unnecessary re-render. One PROBLEM which may be a show stopper for some: it requires adding a property to your object at first render say "_reactKey".

Example for functional component in psuedo TS (ie it won't run in snippets):

interface IRow{

  myData: string,
  _reactKey?:number
  }


export default function List(props: {
    rows: Array<IRow>
}) {
    const {myRows} = props;
    const [nextKey, setNextKey] = useState(100);
    const [rows, setRows] = useState<Array<IRow>|undefined>();


    useEffect(function () {
        if (myRows) {
            for (let row of myRows){
                if (!row._reactKey){
                    row._reactKey = nextKey;
                    setNextKey(nextKey+1);
                }
            }
            setRows(myRows);
        } else if (!rows) {
            setRows([]);
        }
    }, [myRows, columns]);
    
    addRow(){
    
        let newRow = { blah, blah, _reactKey : nextKey};
        setNextKey(nextKey+1);
        rows.push(newRow);
        setRows({...rows});
    
    }
    
    function MyRow(props:{row:IRow}){
        const {row} = props;
        
        return <tr><td>{row._reactKey}</td><td>row.myData</td></tr>
    
    }
    
    return <table>
        <tr><th>Index</th><th>React Key</th><th>My Data</th></tr>
        rows.map((row, key)=>{
            return <MyRow key={row._reactKey} row={row} />
        }
        </table>
        
}
            
    
    
    

Comments

0

I don't use react too much, but the last time I saw this issue I just created a new state array, and tracked the keys there.

const [keys, setKeys] = useState([0]);
const [items, setItems] = useState([value: "", key: 0,])

Then when I add a new item to list, I get the last key from the keys array, add 1, then use setKeys to update the keys array. Something like this:

const addItemWithKey = () => {
  // create a new array from the state variable
  let newKeyArr = [...keys];
  // create a new array from the state variable that needs to be tracked with keys
  let newItemArr = [...items];
  // get the last key value and add 1
  let key = newKeyArr[newKeyArr.length-1] + 1;
  newKeyArr.push(key);
  newItemArr.push({value: "", key: key,});
  // set the state variable 
  setKeys(newKeyArr);
  setItems(newItemArr);
};

I don't worry about removing values from the keys array because it's only being used for iterating in the component, and we're trying to solve for the case where we remove an item from the list and/or add a new item. By getting the last number from the keys array and adding one, we should always have unique keys.

Comments

0

Nowadays (2023) you can use crypto.randomUUID() to generate a UID. This can be used as a proper key. It's supported on all mainstream modern browsers and server-side JS platforms such as node. You should only have issues with this if you need to support IE11 or less.

See this for support details

2 Comments

You end up with the same issue as others have pointed out about the ID being changed on each re-render.
you should assign the uid to the data, keeping it in memory along the item, so the id doesn't change on re-render
0

You can use useID() hook like this :

import {useId, useState } from "react";

function Buttons() {
    const [buttons, setButtons] = useState([
        {
            id: useId(),
            text: "btn1",
        },
        {
            id: useId(),
            text: "btn2",
        },
        {
            id: useId(),
            text: "btn3",
        },
        {
            id: useId(),
            text: "btn4",
        },
    ]);
    return (
         {buttons.map((button) => (
        <button key={button.id}  id={button.id}>
          {button.text}
        </button>
      ))}

    );

One thing to note when using this approach is that you might run into issues if you have to use the document.querySelector method.

The hook creates unique IDs formatted as :r0: and selectors starting with a colon are not valid.

If you need to prefix the unique ID with a value, use a template literal. like this : message${useId()}

Note that you shouldn't use the useId hook to generate values for the key prop of list elements.

see : https://bobbyhadz.com/blog/react-generate-unique-id#generating-unique-ids-for-input-fields-in-reactjs

Comments

0

Basically, Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

It should uniquely identifies a list item among its siblings. And important is that you should not use index of array mentioned in React docs: https://robinpokorny.com/blog/index-as-a-key-is-an-anti-pattern/

From that ideas, there are solutions:

First, using generated unique id from backend resources like id, _id, ...

funtion Component({ items }) {
  return items.map(({id, name}) => {
    return <div key={id}>{name}</>;
  })
}

Second, generated by yourself, using some libs like nanoid or uuid

import {nanoid} from 'nanoid';
import {uuid} from 'uuid';
function generatedIdByTime() {
  return Date.now().toString(); 
}

funtion Component({ items }) {
  return items.map(({id, name}) => {
    return <div key={generatedIdByTime()}>{name}</>; // from generatedIdByTime using browser timer
    return <div key={nanoid()}>{name}</>; // from nanoid
    return <div key={uuid()}>{name}</>; // from uuid
  })
}

Comments

0

I made a lib to manage the cas you don't have a unique id inside your objects react-key-from-object

import { useKeyGen } from 'react-key-from-object'

const DogList = () => {
  const keyGen = useKeyGen();

  return (
    <ul>
      {dogs.map((dog) => (
        <li key={keyGen.getKey(dog)}>
          {dog.name}
          -
          {dog.age}
        </li>
      ))
    </ul>
  );
}

It rely on a weakmap under the hood. The weekmap is destroyed when the component unmount.

Comments

-3

You can use react-html-id to generate uniq id easely : https://www.npmjs.com/package/react-html-id

Comments

-3
import React, {useState} from 'react';
import {SafeAreaView,ScrollView,StyleSheet,Text,View,Dimensions} from 'react-native';
const {width}=Dimensions.get('window');
function sayfalar(){
  let pages=[]
  for (let i = 0; i < 100; i++) {    
    pages.push(<View key={i} style={styles.pages}><Text>{i}</Text></View>)
  }
   return pages
}
const App=()=>{
  return(
    
    <View style={styles.container}>
    <ScrollView horizontal={true} pagingEnabled={true}>
    {sayfalar()}
    
    </ScrollView>
    </View>
  )
}
const styles = StyleSheet.create({
  container:{
    flexDirection:'row',
    flex:1
  },
  pages:{
    width:width
  }
})
export default App;

1 Comment

Please refrain from dumping code-only answer. Remember that you are not only answering to the OP, but also to future readers. Especially if you yourself are a new reader after five year. Thus, please edit the answer to contain an explanation as to why this code answers the question at hand. For more information take the tour and read up on How to Ask.
-6

The fastest solution in 2021 is to use uniqid: Go to https://www.npmjs.com/package/uniqid for more info but to sum up:

  • First in your terminal and your project file: npm install uniqid
  • Import uniqid in your project
  • Use it in any key that you need!
 uniqid = require('uniqid');
                return(
                    <div>
                        <div key={ uniqid() } id={list.name}>
                            <h2 key={ uniqid() }>{list.name}</h2>
                            <ListForm update={lst.updateSaved} name={list.name}/>
                        </div>
                    </div>
                )
            });

Comments

-7

Use the index

const list = ['John','May','Sam'];

var lists = list.map((item, index) => {
        return <div key={index}>{item}</div>;
});

Comments

-21

I am using this:

<div key={+new Date() + Math.random()}>

2 Comments

this will not work as the keys are determined at time of render, therefore not deterministic.
i think that is pretty good idea...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.