i am really stuck on how i can pass searched data which a user types from my search bar in the header component to the main component to be displayed.
Currently if i place a search bar in my main component, it searches very well and data is displayed but for my case i want to search from the header component.
I have seen some solutions on stack overflow but i have failed to come up with a solution.
Below is what i have tried:
//implementing search icon
<Search
placeholder="Search..."
allowClear
size="large"
style={{
paddingTop: "14px",
}}
onSearch={(value) => {
setSearchedText(value)
}}
searchedText={searchedText}
/>
Below is my main component where i want the data to be displayed
const Home = (props) => {
const navigate = useNavigate();
const [items, setItems] = useState([])
const [IsLoading, setIsLoading] = useState(true)
useEffect(() => {
let path = `api/v1/homes?query=${props.searchedText}`
axios.get(path)
.then(res => {
console.log(res)
setItems(res.data)
setIsLoading(false);
})
.catch(err => {
setIsLoading(false);
console.log(err)
})
}, [searchedText])
I have removed some code to make it somehow tidy
2
Answers
I think you should be looking for state management libraries like Redux, Recoil, etc.
Recoil is good for beginners since it’s easy to learn, https://recoiljs.org/docs/introduction/getting-started/
or useContext for less library usage. https://dev.to/hey_yogini/usecontext-for-better-state-management-51hi
I really want to write a code for you, but it actually does not help at all.
You should learn on your own 🙂
You need a common parent component that will keep track of
searchText
and will pass it to theHome
component to display.<Search />
will then useprops.searchText
andprops.setSearchText
and<Home />
will useprops.searchText
.This has to do with the unidirectional dataflow that Reach is based. There are essentially two main ways a components keeps track of it’s data – via
state
andprops
. When eitherstate
orprops
changes the component re-renders to display new data.state
can be set from within the component (usinguseState
hook for example) andprops
is passed to the component from it’s parent. We use can pass callbacks from a parent to its children allow children to update parent’s state. This means you cannot pass data directly between siblings, so you need a common parent.There are other alternatives like
Context
andRedux
, but they all essentially use the same approach under the hood.