We know that we need to use key prop when we are rendering array of elements.
For Example:
function Component() {
const data = ['A', 'B', 'C'];
return <div>{data.map((d) => <div key={d}>{d}</div>)}</div>;
}
But why is key not required when we render elements conditionally using && operator ?
For example:
function Component() {
const data = ['A', 'B', 'C'];
const data1 = data[0];
const data2 = data[1];
const data3 = data[2];
return (
<div>
{data1 && <div>{data1}</div>}
{data2 && <div>{data2}</div>}
{data3 && <div>{data3}</div>}
</div>
);
}
In both cases number of children or order of children can vary. So, why is key only required when we are doing map ?
key is not required when conditionally using && operator, because using it does not change the number/order of children.
For ex, if data2 is null, it's equivalent to
<div>
<div>{data1}</div>
{null}
<div>{data3}</div>
</div>
Even if does not render anything, {null} still counts as an element in the children, so <div>{data3}</div> is still at position 2.
Because children positions are stable between re-renders, there is no need for key.
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