Lifting State in React
Learn to share the search component's state across multiple components.
We'll cover the following...
Currently, the Search component still has its internal state. While we established a callback handler to pass information up to the App component, we are not using it yet. We need to figure out how to share the Search component’s state across multiple components.
The search term is needed in the App to filter the list before passing it to the List component as props. We’ll need to lift state up from Search to App component to share the state with more components.
const App = () => {const stories = [ ... ];const [searchTerm, setSearchTerm] = React.useState('');const handleSearch = event => {setSearchTerm(event.target.value);};return (<div><h1>My Hacker Stories</h1><Search onSearch={handleSearch} /><hr /><List list={stories} /></div>);};const Search = props => (<div><label htmlFor="search">Search: </label><input id="search" type="text" onChange={props.onSearch} /></div>);
We learned about the callback handler previously, because it helps us to keep an open communication channel from Search to App component. The Search component doesn’t manage the state anymore but only passes up the event to the App component after the text is entered into the input field. You could ...