1

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

RESULT IMAGE

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

RESULT IMAGE

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>
  );
}
Swikar
  • 15
  • 3
  • Normally, the header (containing the search bar) should be outside of all routes. So what you wanna do is to be able to access the `history` object outside of routes, right? – Moaaz Bhnas Feb 22 '22 at 06:53
  • If that's the case, here's the solution: https://stackoverflow.com/a/44163399/7982963 – Moaaz Bhnas Feb 22 '22 at 06:56
  • this solution doesn't work in the latest version I tried doing it but the address changes but the component doesn't render, I tried other solutions below but that also doesn't seem to work – Swikar Feb 22 '22 at 07:39
  • Try to create a minimul, running code of your problem that we can work on. Maybe use CodeSandbox – Moaaz Bhnas Feb 22 '22 at 08:06

0 Answers0