Pass arguments to event listeners in ReactJS

Sometimes, you need to pass some data to event listeners. e.g. If you are handling two events with a single event handler and want to pass different data with each event.

It is very easy to pass that data to event listeners in ReactJS. Let us have a look at an example.


class App extends React.Component{
    constructor(props){
      super(props);
      this.state = {
        counter: 0
      };
      this.handleClick = this.handleClick.bind(this);
    }
    handleClick(incrementBy, e){
      e.preventDefault();
      const { counter } = this.state;
      this.setState({
        counter: counter + incrementBy
      });
    }
    render(){
        const { counter } = this.state;
        return (
          <div>
            <div>Total Clicks : {counter}</div>
            <button onClick={this.handleClick.bind(this, 1)}>Increase counter By 1</button>
            <button onClick={(e)=>{this.handleClick(2, e)}}>Increase counter By 2</button>
          </div>
        );
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);
                    

Open above code in codepen.

In above example, we have used arrow function in callback and bind() in event.

In bind() in event, whatever data you want to pass will be passed to bind after this. React event e will be passed as the second argument after data. In arrow function in callback, we have passed arguments explicitly.

Conclusion

In this section, we learned about passing data to event listener in ReactJS.
In the next section, you will learn about controlled components in ReactJS.