datamonkey
datamonkey

Reputation: 43

Execute onClick immediately without getting error

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?

Upvotes: 0

Views: 90

Answers (4)

hurricane
hurricane

Reputation: 6734

You can call it with an arrow function.

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

Upvotes: 1

R.Birol
R.Birol

Reputation: 1

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

Upvotes: 0

Max Filippov
Max Filippov

Reputation: 2092

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.

Upvotes: 1

TheBritishAreComing
TheBritishAreComing

Reputation: 1727

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

Upvotes: 1

Related Questions