...

/

Interactions with Forms and Events

Interactions with Forms and Events

This lesson will explain how to add search functionality by introducing forms and events in React.

We'll cover the following...

We’ll add another interaction to see forms and events in React, a search functionality where the input the search field temporarily filters a list based on the title property of an item.

In the first step, we define a form with an input field in JSX:

Press + to interact
class App extends Component {
...
render() {
return (
<div className="App">
<form>
<input type="text" />
</form>
{this.state.list.map(item =>
...
)}
</div>
);
}
}

In the following scenario you will type into the input field and filter the list temporarily by the search term that is used in the input field. To filter the list based on the value of the input field, we store the value of the input field in the local state. We use synthetic events in React to access a value in an event payload.

Let’s define a onChange handler for the input field:

Press + to interact
class App extends Component {
...
render() {
return (
<div className="App">
<form>
<input
type="text"
onChange={this.onSearchChange}
/>
</form>
...
</div>
);
}
}

The function is bound to the component, so it is a class method again. You just need to bind and define the method:

Press + to interact
class App extends Component {
constructor(props) {
super(props);
this.state = {
list,
};
this.onSearchChange = this.onSearchChange.bind(this);
this.onDismiss = this.onDismiss.bind(this);
}
onSearchChange() {
...
}
...
}

When using a handler in your element, you get access to the synthetic React event in your callback function’s signature.

Press + to interact
class App extends Component {
...
onSearchChange(event) {
...
}
...
}

The event has the value of the input field in its target object, so you can update the local state with a search term using this.setState().

Press + to interact
class App extends Component {
...
onSearchChange(event) {
this.setState({ searchTerm: event.target.value });
}
...
}

Don’t ...

Access this course and 1400+ top-rated courses and projects.