[Help] React OnClick on element

yzap

Isaac de Oliveira Almeida

Posted on September 30, 2024

[Help] React OnClick on element

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,

  • ]); console.log(a); }; return (
    • 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?

  • ๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
    yzap
    Isaac de Oliveira Almeida

    Posted on September 30, 2024

    Join Our Newsletter. No Spam, Only the good stuff.

    Sign up to receive the latest update from our blog.

    Related

    ยฉ TheLazy.dev

    About