React.js Tutorial: Events

 ·  · 

This is a simple demo about how to handle events in React component.

 

1 Prerequisite

You'd better know what a React component is.

2 Handle events in React component

The way of handling events in React component is much similar to DOM events processing in pure JavaScript. You just define a response function and let it be the event handler and listen an event. React.js will be responsible for executing the event handler function when the listened event is detected.

reactjs_component_event_handler

The important difference to which you should pay attention here is that you set a handler via the event props (property) of a React element instead of the event handler attribute of a HTML DOM element. As I said in React component tutorial, the markups in React render function are in fact virtual DOMs (namely ReactElements) rather than real HTML DOM elements.

reactjs_element_event_props

The event objects in React are instances of SyntheticEvent, which is a cross-browser wrapper around the browser's native event. The SyntheticEvent has the same interface as the browser's native event such as stopPropagation() and preventDefault().

You can simply get the underlying native browser event by accessing the nativeEvent attribute of a SyntheticEvent instance.

var nativeEvent = evt.nativeEvent;

There is a list of React supported events in React docs.

 

3 Demo

Simple code snippets to demonstrate how to handle event in React component.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React Events Demo</title>

    <!-- react includes two parts: react.js and react-dom.js -->
    <script src="//fb.me/react-15.2.1.js"></script>
    <script src="//fb.me/react-dom-15.2.1.js"></script>

    <!-- babel standalone -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.10.3/babel.min.js"></script>
</head>
<body>
    <div id="app"></div>

    <script type="text/babel">
        var HelloWorld = React.createClass({
            handleClick: function(e) {
                console.log("getPrototypeOf(event) => ");
                console.log(Object.getPrototypeOf(e));

                console.log("--------------------------");

                console.log("event object => ");
                console.log(e);

                console.log("--------------------------");

                console.log("event.nativeEvent => ");
                console.log(e.nativeEvent);

                console.log("--------------------------");
            },
            handleBlur: function(e) {
                console.log("Input value is => " + e.target.value);
                console.log("--------------------------");
            },
            handleClickWithArgs: function(param, e) {
                console.log("Param passed is => " + param);
                console.log("--------------------------");
            },

            render: function () {
                return (
                    <div>
                        <h3>Event in React.js Component </h3>

                        <button onClick={this.handleClick}>Click me to see the 'event' object in console log!</button>
                        <br/>
                        <br/>

                        <input type="text" defaultValue="" onBlur={this.handleBlur} />
                        <br/>
                        <br/>

                        <button onClick={this.handleClickWithArgs.bind(this, 'React.js Demo')}>Pass param to event</button>
                    </div>
                )
            }
        });

        var App = React.createClass({
            render: function () {
                return (
                    <div>
                        <h1>React Events Demo</h1>
                        <HelloWorld />
                    </div>
                )
            }
        });

        // Mount root App component
        ReactDOM.render(<App />, document.getElementById('app'));
    </script>
</body>
</html>

The output of console.log() in browser's console are as follows.

reactjs_component_SyntheticEvent

You can see from above picture that React wrapped the browser native click event in a SyntheticEvent instance.