[Help] React OnClick on element
Isaac de Oliveira Almeida
Posted on September 30, 2024
I just found out that when you give an element an OnClick attribute with any function, it doesn't store the reference to the function. Instead, it stores the version of the function at that current time. See:
` const showLength = () => {
console.log(a.length);
};
const [a, setA] = useState([
const add = (event) => {
setA([...a,
- add showLength {a}
The output of this is a square, next to two buttons: add, and showLength
Add increases the list and shows another square next to the first one, and showLength shows the current length of the list.
My problem is that the first square also recieved the onClick function showLength, but it always prints "1". Does anyone know how to fix this?
Posted on September 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.