Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you add a key to a React JSX Element after it's instantiated?

Given the following:

function generateWrapper(...elements) {
    return (
        <div>
            {...elements}
        </div>
    );
}

ReactDOM.render(
    generateWrapper(
        <MyElement name="first" />,
        <MyElement name="second" />,
    ),
    document.getElementById("app"),
);

React will rightfully complain that I haven't added a key property to each of the children of the wrapper div. How can I do this? Or is this against the spirit of react development? Thanks for any answers in advance!

PS: Yes there is a similar question I looked at but it seemed to be targeting users not using JSX

PPS: I do realize I can merely add a key to first and second MyElement's but this is what I'm attempting to avoid

edit: Changing code to better suit my circumstances

like image 890
Right2Drive Avatar asked Jul 17 '17 23:07

Right2Drive


People also ask

How do you assign a key in React?

Keys should be given to the elements inside the array to give the elements a stable identity: const numbers = [1, 2, 3, 4, 5]; const listItems = numbers.map((number) => <li key={number.toString()}> {number} </li> ); The best way to pick a key is to use a string that uniquely identifies a list item among its siblings.

Do you need to add key property on Reactjs elements?

Almost every React application displays an array list of some kind using the method map. And React tells us that for each element of that list that we return for rendering, we must provide a unique key prop.

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.

What is key attribute in JSX?

According to the react documentation: A key is a special string attribute you need to include when creating lists of elements. Keys help react identify which elements have changed, have been deleted or added. It gives the elements in the array a stable identity.


1 Answers

Take a look at React.cloneElement. You could use that to create and attach the key property inside your generateWrapper method.

function generateWrapper(...elements) {
  return (
    <div>
      {
        elements.map(element =>
          React.cloneElement(element, { key: 'your-unique-key-here' })
      }
    </div>
  );
}
like image 116
Danny Delott Avatar answered Oct 24 '22 06:10

Danny Delott