Paulos3000 Paulos3000 - 1 year ago 75
Javascript Question

Passing values to .bind() method

If I am calling an event handler function, I know I can use

to pass the bound
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 -
- is my event object, but I want to pass
as well.

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

Where am I going wrong?

Answer Source

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

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)} />
  <MyForm todoListLength={10} userId={"tjc"} />,
<div id="react"></div>
<script src=""></script>
<script src=""></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download