i want to compare two react tsx elements. i am still new to react and tsx. but i am unale to do so even after copying and pasting the exact elements to compare. Can you tell me why and how to fix it?
Here is where i want to compare
function placeTile(index: number) {
if (
tiles[index] === //Compare here
(
<div className="filler" id=".">
.
</div>
)
) {
let updateTile = tiles.slice();
updateTile[index] = (
<div className="filled" id={move}>
{move}
</div>
);
console.log("Filled a spot");
setTiles(updateTile);
} else {
console.log("This is filled spot " + index);
}
}
The ’tiles’ is an array of the very same tsx elements declared as follows
let createTileSetup = Array(9).fill(
<div className="filler" id=".">
.
</div>
);
const [tiles, setTiles] = useState(createTileSetup);
Using something like tiles[index].id
to get the id isnt working. It is just saying it is undefined
If there is another way please tell me. their ids are different but i dont know how to compare those either. any help is appreciated
2
Answers
The reason your strategy doesn’t work is because for Javascript objects, the
===
operator tests for identity (ie: whether they refer to the same object) rather than any sort of equivalence structurally.To fix this, use some other test to check for equality of the objects. To test, for example, the className of your
<div>
s, you could writeBe wary that if you do this, you must also check that each
tiles[index]
is indeed an HTML tag. Otherwise,tiles[index].props.className
may cause an erroraccessing property className of undefined
.Hope this helps.
compare properties of the elements rather than the elements themselves. instead of directly comparing JSX elements, compare the id property of the tiles. If the id matches the expected value (in this case "."), update the tile at the specified index.