Home > Blockchain >  Execute onClick immediately without getting error
Execute onClick immediately without getting error

Time:09-27

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?

CodePudding user response:

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)}

CodePudding user response:

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.

CodePudding user response:

You can call it with an arrow function.

onClick={() => functionExample("stringParam", true)}

CodePudding user response:

In your code you invoked a function which is named "functionExample" then assign the return value of this function to onClick. You have to assign a callback function to "onClick" and inside of that function you need to call "functionExample" function like below.

onClick={() => functionExample("stringParam", true)}
  • Related