Skip to content
This repository has been archived by the owner on Jul 10, 2020. It is now read-only.

Latest commit

 

History

History
77 lines (60 loc) · 2.95 KB

11-react-use-event-handlers-with-react-bd53256d.md

File metadata and controls

77 lines (60 loc) · 2.95 KB

11. Use Event Handlers with React

Notes

  • There are a ton of supported events that you can find on the docs. Let’s get an introduction to event handlers with React.

  • We still haven’t gotten to state yet, so we’ve implemented our own little way of managing state and re-rendering our component so we can play around with event handlers.

  • One thing you’ll want to know is that events with React are very similar to working with events in regular DOM.

<body>
  <div id="root"></div>
  <script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
  <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
  <script type="text/babel">
    const rootElement = document.getElementById('root');

    // The current state of our app
    const state = { eventCount: 0, username: '' };

    function App() {
      function handleClick() {
        setState({ eventCount: state.eventCount + 1 });
      }

      function handleChange(event) {
        // Getting current value from the input
        console.log(event);
        // Getting the SyntheticEvent
        console.log(event.nativeEvent);
        // Getting the nativeEvent if needed
        setState({ username: event.target.value });
      }

      return (
        <div>
          <p>There have been {state.eventCount} events.</p>
          <p>
            {/* We can have different types of events here that are supported by React: https://reactarmory.com/guides/react-events-cheatsheet */}
            <button onClick={handleClick}>Click Me</button>
          </p>
          <p>You typed: {state.username}</p>
          <p>
            <input onChange={handleChange} />
          </p>
        </div>
      );
    }

    // This is generally not how you handle state
    function setState(newState) {
      Object.assign(state, newState);
      renderApp();
    }

    function renderApp() {
      ReactDOM.render(<App />, document.getElementById('root'));
    }

    renderApp();
  </script>
</body>
  • React does have an optimization implementation on top of the event system called SyntheticEvents, but most of the time you won’t observe any difference with those events from regular DOM events (and you can always get access to the native event using the nativeEvent property).

Additional resource