How to print a variable in html tag

Why variable a is undefined

export default function Surah() {
  let a;
  const toDo= (id) => {
    a = id;
    console.log(a);
  };

  return (
      <div>
        <div>
          <button onClick={() => toDo(1)}></button>
          <div>{a}</div>
        </div>
      </div>
  )
}

is my code wrong? please help solve it

>Solution :

you need to use `a as state variable

import {useState} from "react";

export default function Surah() {
  const [a, setA] = useState();
  const toDo= (id) => {
    setA(id);
  };

  return (
      <div>
        <div>
          <button onClick={() => toDo(1)}></button>
          <div>{a}</div>
        </div>
      </div>
  )
}

Leave a Reply