0

So here's my code, I was wondering on why whenever I click on the button, it always return a Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')? How can I resolve this case?

import React from "react";

export default function GameApp() {
  const score = 0;
  const firstNum = document.getElementById("card1");
  const secondNum = document.getElementById("card2");
  const thirdNum = document.getElementById("card3");

  // starting the game
  function start() {
    firstNum.innerHTML = "First number: " + Math.floor(Math.random() * 13 + 1);
    secondNum.innerHTML =
      "Second number: " + Math.floor(Math.random() * 13 + 1);
  }

  function deal() {
    thirdNum.innerHTML = "Third number: " + Math.floor(Math.random() * 13 + 1);
  }

  return (
    <div>
      <button onClick={start}> Start the game </button>
      <p id="card1"> </p>
      <p id="card2"> </p>
      <p id="card3"> </p>
      <button onClick={deal}> Deal </button>
    </div>
  );
}
woopsies
  • 11
  • 2
  • 1
    Please read the https://reactjs.org/ docs. You don't manipulate dom elements directly in React unless absolutely necessary. – orel Mar 22 '22 at 08:00
  • Also it looks like you are trying to access those elements by id before you create them, but as @orel wrote - this is not how React is supposed to work – Iorweth333 Mar 22 '22 at 09:00

0 Answers0