If they are siblings, they are still children of another parent element. So they are still technically children.
This would trigger a: Warning: Each child in a list should have a unique “key” prop.
const Foo = () => <div>Foo</div>
const Bar = () => <div>Bar</div>
const App = () => {
return (
<React.Fragment>
<Foo key="baz" />
<Bar key="baz" />
</React.Fragment>
);
};
ReactDOM
.createRoot(document.getElementById("root"))
.render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
As expected, we are presented with the following error:
Warning: Encountered two children with the same key, baz
. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
Chris' response to "Understanding unique keys for array children in React.js" explains all you need to know about they key
prop.
He cites the React docs:
Keys Must Only Be Unique Among Siblings
Keys used within arrays should be unique among their siblings. However, they don’t need to be globally unique.
In conclusion, since they are siblings (disregarding component type), each key
prop should be unique.
Since we can re-use keys (non-global), we can actually do the following:
const MyComponent = () => (
<div>
<div key="a">a</div> {/* Local, will be rendered n-number of times */}
<a key="b" href="#">b</a> {/* Same as above... */}
</div>
)
const App = () => {
return (
<React.Fragment>
<MyComponent key="foo" /> {/* Will render 'a' and 'b' */}
<MyComponent key="bar" /> {/* Will render 'a' and 'b' */}
</React.Fragment>
);
};
ReactDOM
.createRoot(document.getElementById("root"))
.render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
Note: Keep in mind that you should only have to supply a key when mapping over an array of items.