Handling React Events

Handling React Events is not too dissimilar to using pure JavaScript on DOM elements.

For click events, a camel-cased onClick attribute is used as opposed to the standard onclick.

In addition, the value within onClick uses the JSX syntax and is not a string.

<button onClick={this.handleClick}>Click me!</button>

This can be written within a React component class like the following.

class ButtonElement extends React.Component {
    constructor(props) {
      super(props);
    }
    handleClick() {
      alert('Button clicked!');
    }
    render() {
      return (
        <button onClick={this.handleClick}>Click me!</button>
      );
    }
}

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

The button element will be rendered within the DOM and the JavaScript alert will show when the button is clicked.

Handling React Events

Similar to standard JavaScript, use the preventDefault() Event method to stop the default action of an element from happening.

This is particularly useful if adding a click event to an anchor link that contains a href="#" attribute. This will stop the default behaviour of the page jumping to the top.

class ButtonElement extends React.Component {
    constructor(props) {
      super(props);
    }
    handleClick(e) {
      e.preventDefault();
      alert('Link clicked!');
    }
    render() {
      return (
        <a href="#" onClick={this.handleClick}>Click me!</a>
      );
    }
}

It should be noted that in React, you cannot use return false to prevent an element’s default behaviour, so make sure you use preventDefault().