my React Webapp has some strange behaivior, I have implemented a global edit mode, which can be activated and deactivated, the state variable which controls this gets passed by a ContextProvider. When activated, a button gets inserted into the DOM, which can open up a form.
{edit ?
<button
onClick={setShowLinkForm(true)}
className="btn card w-36 h-36 bg-base-100 hover:bg-slate-700 shadow-xl items-center justify-center p-4 glassmorphism cursor-pointer"
>
<svg className="w-12" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" >
<path stroke-linecap="round" stroke-linejoin="round" d="M12 9v6m3-3H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</button>
: "" }
Now the strange thing is, when the button gets inserted, it triggers the onClick event automatically, is there any workaround besides controlling the activation and deactivation with CSS?
Edit: People suggest i need to call the function "setShowLinkForm" in a callback, i did that it now looks like this:
onClick={() => {
setShowLinkForm(true);
}}
Now it gets even stranger, the event still gets triggered on insertion and as long as "edit" is true, which means the button is inserted it somehow blocks the state of "showLinkForm" which gets changed by "setShowLinkForm". If edit is false and the Button is removed, the state "showLinkForm" is changeable again.
CodePudding user response:
You're immediately invoking the function in the onClick
prop.
Replace onClick={setShowLinkForm(true)}
with onClick={() => setShowLinkForm(true)}
CodePudding user response:
that function runs regardless, try this
<button
onClick={() => {
yourFunc(true);
}}
>
Click me to run onclick
</button>