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:
JavaScript
x
13
13
1
const Home = () => {
2
return (
3
<>
4
<Navigation />
5
<SearchBar />
6
<Wrapper>
7
<Filters />
8
<ProductsList />
9
</Wrapper>
10
</>
11
);
12
}
13
I have search state in SearchBar component, and need to pass it to ProductList component
JavaScript
1
16
16
1
const [search, setSearch] = useState('');
2
3
const handleSetSearch = (e) => {
4
setSearch(e.target.value);
5
}
6
7
return (
8
<Wrapper>
9
<StyledTitle>inPal Search</StyledTitle>
10
<InputWrapper>
11
<StyledInput type="text" placeholder="Write something..." onChange={(e) => handleSetSearch(e)} />
12
<SearchIcon src={searchIcon} alt="Search" />
13
</InputWrapper>
14
</Wrapper>
15
);
16
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:
JavaScript
1
16
16
1
const Home = () => {
2
3
const [search, setSearch] = useState('');
4
5
return (
6
<>
7
<Navigation />
8
<SearchBar search={search} setSearch={setSearch} />
9
<Wrapper>
10
<Filters />
11
<ProductsList search={search} />
12
</Wrapper>
13
</>
14
);
15
}
16