I have a modal in React JS where I want to execute a function upon opening the modal. This is a button function and it works completely fine so far by having it like so:
<button onClick={functionExample("stringParam", true)} id='buttonId' className="buttonClass" />
The only issue with this is that it throws this error:
index.js:1 Warning: Expected `onClick` listener to be a function, instead got a value of `object` type.
Is there any way to do this without getting the error?
You can call it with an arrow function.
onClick={() => functionExample("stringParam", true)}
You have to pass a function, which will be later called by React like this:
<button onClick={() => functionExample("stringParam", true)} id='buttonId' className="buttonClass" />
When you do JS "stores" the function for later execution, but if you write
onClick={functionExample("stringParam", true)}
your code gets execute in place, returns an object and this is what React complaining about.
Your onClick listener is a calling the method on render instead of onClick
<button onClick={() => functionExample("stringParam", true)} id='buttonId' className="buttonClass" />
Change your onClick to
onClick={() => functionExample("stringParam", true)}