Skip to content

5 input

Ben Foley edited this page Aug 9, 2019 · 1 revision

Let's handle some input

Make a new toy app to handle receiving user input.

cd ~/sandbox
npx create-react-app react-input
cd react-input
yarn start

We can do all this in App.js.

  1. Remove the unused stuff from App.js to get back to basics (delete the logo line, and the tags inside the header tag).
  2. Change it from being a functional/stateless component to a class component (so we can use state). See the example code below for guidance, or review the previous workshop for more info.
  3. Create a state object to handle the data. Here's the code so far...
import React from 'react';
import './App.css';

class App extends React.Component {

  state = {name: "me"}

  render() {
    return (
      <div className="App">
        <header className="App-header">
        </header>
      </div>
    )
  }
}

export default App;
  1. Now, add an input tag and a function to handle the input. The tag has an onChange property which refers to the handleChange function. Whenever the input is changed (eg, a user types in it), the function gets an event object. One of the properties of the event is a target object, which itself has a value property! Turtles all the way down...

In this example, the handle function updates the local state with the value that is typed into the field.

  1. In the render function we also draw the state name value.
import React from 'react';
import './App.css';

class App extends React.Component {

  state = {name: "me"}

  handleChange = (event) => {
    this.setState({name: event.target.value})
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <input type="text" onChange={this.handleChange} />
          <br />
          <p>{this.state.name}</p>
        </header>
      </div>
    )
  }
}

export default App;

So in summary, when the input changes, the handleChange function is called, and it updates state.

Clone this wiki locally