Paulos3000
Paulos3000

Reputation: 3545

Passing values to .bind() method

If I am calling an event handler function, I know I can use .bind(this) to pass the bound this value, but how to I pass extra arguments to the function call?

I have this:

onSubmit={this.handleSubmit.bind(this, todoListLength, userId)}

Then my function definition is like so:

handleSubmit(e, id, userId) { 
   console.log(userId) // returns nothing
   console.log(id) // returns nothing
}

The first argument - e - is my event object, but I want to pass id and userId as well.

But when I try to log the value, in my handleSubmit definition, it returns nothing.

Where am I going wrong?

Upvotes: 2

Views: 2111

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

Arguments you bind to the function will be supplied to it before the ones that the bound function receives. So your function should declare its parameters with e at the end:

handleSubmit(id, userId, e) { 
   console.log(userId);
   console.log(id);
}

Here's an example, using onClick instead of onSubmit because Stack Snippets don't like forms:

class MyForm extends React.Component {
  handleSubmit(id, userId, e) {
    // Note: `id` seems an odd name for the todoListLength argument ;-)
    console.log("id = " + id);
    console.log("userId = " + userId);
    console.log("e.type = " + e.type);
  }
  
  render() {
    let {todoListLength, userId} = this.props;
    return (
      <input type="button" value="Click Me" onClick={this.handleSubmit.bind(this, todoListLength, userId)} />
    );
  }
}
ReactDOM.render(
  <MyForm todoListLength={10} userId={"tjc"} />,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Upvotes: 4

Related Questions