How to learn react logo

These tutorials will give you a deeper understanding of React.js. Learn with examples from the Javascript UI library, covering the basics and the advanced.

Browse by tag:

Responding to events triggered by user interaction

DOMEvents

In Web development everything you do is based around the Document Object Model (DOM). The DOM has built into it an event loop that listens for changes across some part of the UI. To access that event loop in the Virtual DOM the react team put together what is called the Synthetic Event so that we can pretty much have access to all the events we would need to provide users with an interactive web application. Learn to harness the power of events in React and you’ll be set to build out React Web Applications.

How do we take in user input via forms, respond to clicks, mouse events and scrolling? Here is a statement straight from the React Docs

Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences:

  • React events are named using camelCase, rather than lowercase.
  • With JSX you pass a function as the event handler, rather than a string.

Below are three examples of different handlers (onClick, onDoubleClick, onChange) and different outputs (alert, console.log, this.setState)

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      someValue: '',
    }
  }  

  clickHandler = () => alert("Single Click!");
  doubleClickHandler = () => console.log("Double Clicked!");
  changeHandler = event => {
    this.setState({ someValue: event.target.value });
  };

  render() {
    return (
      <div className="App">
        <h1>Hello Handlers</h1>
        <h2>Lets build out some handler functions.</h2>
        <button onClick={this.clickHandler}>Click Handler Demo</button>
        <button onDoubleClick={this.doubleClickHandler}>Double Click Handler</button>
        <input onChange={this.changeHandler} placeholder="Change my input" />
        <p>To get this output: {this.state.someValue}</p>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

How To Learn React is designed and developed by me, Blake Fletcher. It is a project intended to share the things I learn while working with the UI library. As I build things, complete tutorials, read blog posts, and watch videos, I'll add to the site. I hope to eventually bring on other contributors. If interested, send me an email at blkfltchr@gmail.com.