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
CodePudding user response:
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>
)
}
CodePudding user response:
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>
)
}