So I am making a Search Functionality On My Recent E-Commerce Project Where I Got Stuck On A Problem Where I Do The React Rendering Because I Cannot Simply Write The Search Component In The (Header Component) Which Displays The Search Bar If Written Without Using Any Kind Of Route But The Problem Is I Need To Pass In The Props As Well Below Is The Error To What I Mean :
Code Without Route
<div className="col-12 col-md-6 mt-2 mt-md-0">
<Search />
</div>
The Result
Code With Route In It
<div className="col-12 col-md-6 mt-2 mt-md-0">
<Routes>
<Route render={({ history }) => <Search history={history} />} />
</Routes>
</div>
The Result
So What I Want To Do Is Render The Search Component While Using The Route So That I Can Pass In The Props To It
Search Component Code
const Search = ({ history }) => {
const [keyword, setKeyword] = useState("");
const searchHandler = (e) => {
e.preventDefault();
if (keyword.trim()) {
history.push(`/search/${keyword}`);
} else {
history.push("/");
}
};
return (
<form onSubmit={searchHandler}>
<div className="input-group">
<input
type="text"
id="search_field"
className="form-control"
placeholder="Enter Product Name ..."
onChange={(e) => setKeyword(e.target.value)}
/>
<div className="input-group-append">
<button id="search_btn" className="btn">
<i className="fa fa-search" aria-hidden="true"></i>
</button>
</div>
</div>
</form>
);
};
App.js Code
function App() {
return (
<Router>
<div className="App">
<Header />
<div className="container container-fluid">
<Routes>
<Route path="/" element={<Home />} exact />
<Route path="/search/:keyword" element={<Home />} />
<Route path="/product/:id" element={<ProductDetails />} />
</Routes>
</div>
<Footer />
</div>
</Router>
);
}