i want to share props from components to sibling children. I’ve read about React Context but can’t implement it.
My home component looks like this:
const Home = () => { return ( <> <Navigation /> <SearchBar /> <Wrapper> <Filters /> <ProductsList /> </Wrapper> </> ); }
I have search state in SearchBar component, and need to pass it to ProductList component
const [search, setSearch] = useState(''); const handleSetSearch = (e) => { setSearch(e.target.value); } return ( <Wrapper> <StyledTitle>inPal Search</StyledTitle> <InputWrapper> <StyledInput type="text" placeholder="Write something..." onChange={(e) => handleSetSearch(e)} /> <SearchIcon src={searchIcon} alt="Search" /> </InputWrapper> </Wrapper> );
Can someone help me to understand this?
Advertisement
Answer
You can declare the state in parent component (Home
) and pass it as prop to both the child components as:
const Home = () => { const [search, setSearch] = useState(''); return ( <> <Navigation /> <SearchBar search={search} setSearch={setSearch} /> <Wrapper> <Filters /> <ProductsList search={search} /> </Wrapper> </> ); }