react-container
Goals
Create a
SearchBoxcomponent to list only robots that match the search termKey inputs are handled by
SearchBox, but robots are being provided by parent componentWe need some way to integrate the two
Solution:
Make the search box and display stateless (display) components
Use the parent as a common third party to hold the data
Main Application
class App extends Component {
constructor() {
super()
this.state = {
searchTerm: "",
robots: robots
}
}
onSearchChange = (evt) => {
this.setState({searchTerm: evt.target.value})
}
render() {
const { searchTerm, robots } = this.state;
const filteredRobots = robots.filter(robot =>
robot.name.toLowerCase().includes(searchTerm.toLowerCase())
);
return (
<div className="tc">
<h1>RoboDex</h1>
<SearchBox onSearchChange={this.onSearchChange}/>
<CardList robots={filteredRobots} />
</div>
);
}
}How It Works
Note how
onSearchChangeis passed down toSearchBoxRemember, every
setStatecall triggers re-renderingSearchBoxdoesn't need to care whose state it is updating
Also note how
filteredRobotsis set by filtering entire robot listDo not modify the main list, since we don't want to throw robots away
Again,
CardListdoesn't care which list it is displaying
Search Box
const SearchBox = (props) => {
const { onSearchChange } = props;
return (
<div className="pa2">
<input className="pa2"
type="search"
placeholder="search Robots..."
onChange={onSearchChange}
/>
</div>
);
};In principle, this is re-rendered on each keystroke because of the parent's state change
React does work behind the scenes to minimize work
Last updated
Was this helpful?