One of the trickiest parts of learning React is understanding forms and events. In this short tutorial we will create a form and output its content, in real-time, to the webpage. You should already have create-react-app installed.

To start, create a new React app and change into its directory.

$ create-react-app realtime-input
$ cd realtime-input
$ npm start

The final command will start the server and open a webpage at http://localhost:3000/.

The only file we need to change is App.js. In your text editor, remove much of the default text and add a basic input form.

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div>
        Change name: <input type="text" />
      </div>
    )
  }
}


export default App;

Now we want a way to access the event payload of our input which we can do with onChange, a React synthetic event. We need to capture the payload and store it in our local state. In React data flows down in a unidirectional way from parent to child components. In this case we’re sending data up from a component to the state so we must use a callback function.

Callbacks are a core part of JavaScript and allow us to pass in functions as arguments. We’ll create a handler callback function handleChange which will “handle” the result of our event payload. Then we need to bind this new method to our App component and update the state with setState().

Here is the updated code.

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      username: 'wsvincent'
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.setState({
      username: e.target.value
    });
  }

  render() {
    return (
      <div>
        Hello {this.state.username} <br />
        Change name:
        <input type="text" value={this.state.username} onChange={this.handleChange} />
      </div>
    );
  }
}

export default App;

If you try webpage at http://localhost:3000/ now you’ll see that whatever is typed in the input form is then outputted above.

To review:

  • we created an input and then used onChange to capture the event payload in a callback function called handleChange
  • added a value to make our input a controlled component
  • wrote a handleChange method and accessed the event payload e to update username with the value of the input
  • bound handleChange to our App component
  • set an initial value for username

Once you internalize how callback functions work with forms and events, much of React makes a lot more sense.




Want to learn more React? I have a list of recommended React books and JavaScript books.