Repository navigation
5 input
Ben Foley edited this page Aug 9, 2019
·
1 revision
Make a new toy app to handle receiving user input.
cd ~/sandbox
npx create-react-app react-input
cd react-input
yarn startWe can do all this in App.js.
- Remove the unused stuff from App.js to get back to basics (delete the logo line, and the tags inside the header tag).
- 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.
- 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;- Now, add an input tag and a function to handle the input. The tag has an
onChangeproperty which refers to thehandleChangefunction. Whenever the input is changed (eg, a user types in it), the function gets aneventobject. One of the properties of the event is atargetobject, which itself has avalueproperty! Turtles all the way down...
In this example, the handle function updates the local state with the value that is typed into the field.
- 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.