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
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.
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.
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.
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.
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>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With