Onclick() Works On The First Click Only - React
I am trying to make onClick() function work for every button (its the same result), but as of now onClick() works only once. If I click on a button again (the same or different) th
Solution 1:
Your pop function code only sets the state to true, so it will never be false again. You may change it like this.
constpop = () => {
setPop(!isPopped);
};
Solution 2:
in your case setPop
can take boolean value OR method that returns boolean.
Best practices for handle toggling in React looks like:
constpop = () => {
setPop(currentValue => !currentValue);
};
Also, use useCallback
hook to manage events like click and avoid re-initialization of your method on each render:
const pop = useCallback(() => {
setPop(currentValue => !currentValue);
}, []);
Post a Comment for "Onclick() Works On The First Click Only - React"