Said Al-Ghiyats
Said Al-Ghiyats

Reputation: 23

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>
  )
}

Can you explain what is wrong with my code ?

Upvotes: 1

Views: 365

Answers (2)

Abasaheb Gaware
Abasaheb Gaware

Reputation: 547

you need to use a as state variable.

changing the variable value doesn't trigger the component to render again with the updated value, for this updated value you need to render the component again using setState.

import {useState} from "react";

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

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

Upvotes: 0

Mohammad Aaqib
Mohammad Aaqib

Reputation: 19

this is not an optimal way of using the variables. Instead we should useState hook. I'm attaching the code snippet below for your reference.

import {useState} from "react";

export default function Surah() {
  const [a,setA] = useState(0); // Initialize it with a number
  const Tafsir = (id) => {
    setA(id);
  };

  return (
      <div>
        <div>
          <button onClick={() => {
           Tafsir(1);
           console.log(a);
          }}>Click Here</button>
          <div>{a}</div>
        </div>
      </div>
  )
}

Upvotes: 1

Related Questions