Tom Rudge
Tom Rudge

Reputation: 3272

Props not getting passed to onClick function

I have a onClick that uploads data, I need to pass props to that onclick function from the render its in.

onClick={this.handleEditsUpload}

to

handleEditsUpload() {
  const { selected } = this.props;
}

selected is showing as selected: [] in handleEditsUpload().

I have tried passing the props by doing:

onClick={this.handleEditsUpload(...this.props)}

which I thought would work as I am doing this elsewhere.

Not sure where to go from here, any suggestions please?

Upvotes: 0

Views: 351

Answers (2)

Hemadri Dasari
Hemadri Dasari

Reputation: 33974

You no need to specifically pass props to handleEditsUpload event handler function

Change

  onClick={this.handleEditsUpload(...this.props)}

To

 onClick={this.handleEditsUpload}

Because this.props are available directly inside handleEditsUpload.

What you need to make sure is that whether you did binding for handleEditsUpload in constructor. if not then add below line in constructor

      this.handleEditsUpload = this.handleEditsUpload.bind(this);

So now you will have access to props inside handleEditsUpload function

    handleEditsUpload(){
         const { selected } = this.props;
    }

There is no need for passing props to handler function hence I don’t recommend doing that. If you still want to do in that approach then call the function in arrow way because you need to pass params

   onClick={() => this.handleEditsUpload(...this.props)}

Upvotes: 2

AVAVT
AVAVT

Reputation: 7133

You are sending onClick a function's result instead of its reference. What happen during onClick={this.handleEditsUpload(...this.props)} is that handleEditsUpdload is called with the provided props, then its return value (null in this case) is assigned to onClick.

If you want to call handleEditsUpload when the button is clicked, give it a function reference instead:

onClick={() => this.handleEditsUpload(...this.props)}

The difference is that this time you're assigning the arrow function () => this.handleEditsUpload(...this.props) to onClick, instead of a return value.

Upvotes: 1

Related Questions