React

React events – How to handle

event

React events use camelCase for syntax.

Below is an html example.

<button onclick="handleProcessing()">
  Start processing
</button>

See the corresponding React event handling example.

<button onClick={handleProcessing}>
  Start Processing
</button>

For preventing a default event action, you need to explicitly call e.preventDefault().

function PreventDefaultExample() {
  function handleClick(e) {
    e.preventDefault();
    console.log('Link was clicked but default action was prevented.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click this link
    </a>
  );
}

Just wanted to clarify that the e event in handleClick is not an original event emitted but a wrapper cross browser event created by React. It is also known as synthetic event.

React Event Listener best practice

In React we should not typically use addEventListener to a DOM element. Instead we provide the listener when the event is rendered.

One more important point, (this is not a react feature but Javascript feature). In Javascript class methods are not bound by default and you have to explicitly bind them.

class BindingExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isSystemOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state => ({
      isSystemOn: !state.isSystemOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        System Is {this.state.isSystemOn? 'ON' : 'OFF'}
      </button>
    );
  }
}

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

See it live in action here.

https://codepen.io/anilpank/pen/VwZgwjY

Simple way to remember this is if you refer a method without () after it, such as onFocus={this.handleFocus}, you should bind this method. And a good place to bind it is in component class constructor.

How to pass arguments to event handlers in React

There are cases where you want to pass some arguments to React event handlers. Again bind comes to the rescue. You can pass and access as many arguments as you want as well as the event as last argument.

class Plan extends React.Component {
    
   handleClick(planName, planCategory, e) {
      alert('planName:'+ planName + ' planCategory:' + planCategory + ' event' + e);
   }

   render() {
     let planName = 'Business Plan';
     let planCategory = 'Success';
     return (
              <button onClick={this.handleClick.bind(this,planName, planCategory)}>
                 Plan Me
              </button>
            );
      }
}

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

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

About anil

Hi, I'm Anil Verma. I have a passion for teaching and developing awesome front end apps. I was involved in development of post processor for Nastran(built by NASA). More recently I have been building supply chain apps at E2open.
View all posts by anil →

Leave a Reply

Your email address will not be published. Required fields are marked *