javascripthtmltypescriptreact-typescripttsx

How to compare two tsx elements in react + tsx


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


Solution

  • 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 write

    
    if (
          // .props.className gets the className of an HTML tag
          tiles[index].props.className === 'filler'
        )
    {
        // Do something
    }
    

    Be 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 error accessing property className of undefined.

    Hope this helps.