Skip to content

Instantly share code, notes, and snippets.

@SASUKE40
Created June 14, 2018 08:32
Show Gist options
  • Select an option

  • Save SASUKE40/e46e2376a461ed84cd444be40eaae213 to your computer and use it in GitHub Desktop.

Select an option

Save SASUKE40/e46e2376a461ed84cd444be40eaae213 to your computer and use it in GitHub Desktop.
class Example extends Component {
state = {
filterText: "",
};
// *******************************************************
// NOTE: this example is NOT the recommended approach.
// See the examples below for our recommendations instead.
// *******************************************************
static getDerivedStateFromProps(props, state) {
// Re-run the filter whenever the list array or filter text change.
// Note we need to store prevPropsList and prevFilterText to detect changes.
if (
props.list !== state.prevPropsList ||
state.prevFilterText !== state.filterText
) {
return {
prevPropsList: props.list,
prevFilterText: state.filterText,
filteredList: props.list.filter(item => item.text.includes(state.filterText))
};
}
return null;
}
handleChange = event => {
this.setState({ filterText: event.target.value });
};
render() {
return (
<Fragment>
<input onChange={this.handleChange} value={this.state.filterText} />
<ul>{this.state.filteredList.map(item => <li key={item.id}>{item.text}</li>)}</ul>
</Fragment>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment