Home > Blockchain >  getElementById right after it's created
getElementById right after it's created

Time:11-13

im working in React. I have a map() function on an array that creates a div for each object in the array and assigns it an id:

 {squares.map((element) => {
            return (
              <div key={element} id={element} className="square">
                {element}
              </div>
            );

I also created a function to select a div by id and color it:

 const colorRed = () => {
    document.getElementById("1").style.backgroundColor = "red";
  };

if I call on the function, it returns an error because document.getElementById("1") is null, because at first there is no such element.

I tried conditioning it with:

{ document.getElementById("1") && colorRed()}

so that it only runs the function if the getElement is true. and it worksm sort of, but only on the second instance. the first rendering of map (triggered by a button click event) runs without error but no red background.

how do i join these functions or where should I call the colorRed function for it to apply imideatly when an elemnt of that id is created?

by the way, the end goal is to insert an image to the div, not color it. but appendChild didn't work at all so first thing first i'm trying to get the element right away.

I tried selecting the element the moment it is created and coloring it red. when I conditioned it with && it worked but only on the second time it was rendered, and every time after that.

the code in it's entirety:

function App() {
  const [squares, setSquares] = useState([]);
  const shuffleSquares = () => {
    const nowShuffledSquares = [...squaresValue].sort(
      () => Math.random() - 0.5
    );

    setSquares(nowShuffledSquares);
  };

  const colorRed = () => {
    document.getElementById("1").style.backgroundColor = "red";
  };
  return (
    <div className="container">
      <div className="btn-container">
        <button className="shuffle" onClick={shuffleSquares}>
          shuffle
        </button>
      </div>
      <div className="board-container">
        <div className="board">
          {squares.map((element) => {
            return (
              <div key={element} id={element} className="square">
                {element}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

export default App;

CodePudding user response:

Edited

i've tested out the useRef() code and it seems to be working for me.

i made this code sanbox example

onLoad was my mistake it seems that it only works for <img />

you can also simply use a condition on the style prop:

<div
    key={element}
    id={element}
    className="square"
    style={{backgroundColor: element === 1 ? 'red' : ''}}
    {element}
</div>
  • Related