Here I have the state, and I am trying to pass them into child component SearchBar
App Component (parent component)
// not related code ...
// search
const { search, setSearch } = useState("");
const handleSearch = (e) => {
setSearch(e.target.value);
};
// not related code ...
return (
<ContextProviders
// not related code ...
>
<div className="App">
<Navbar />
<SearchBar search={search} handleSearch={(e) => handleSearch(e)} />
<Outlet />
</div>
</ContextProviders>
);
}
Into SearchBar when I am typing something in order to trigger setState it shows up an error:
SearchBar (child component)
import { useState } from "react";
export default function SearchBar(props) {
// not related code ...
console.log(props);
return (
<>
<div>
<input
type="search"
value={props.search}
onChange={props.handleSearch}
// not related code ...
/>
</div>
</>
);
}
I need to get the value from the input field in the search component(child) into App component(parent), I try to pass a function which sets state into App, but it doesn’t work, I get the error:
Uncaught TypeError: setSearch is not a function at handleSearch
Does anyone see the issue here?
2
Answers
why did you pass the anonymous arrow function in handleSearch? you just need to point handleSearch function. There is no need to call it.
You should initialize your state as:
And pass the
handleSearch
function like this: