I have two components. A SearchBar and a NavBar. In the homepage I have the searchBar in the middle but when I input something for the first time, I have redirected the user to another page where the SearchBar component gets nested into the Navbar and the suits get displayed.
What is a good/best way to achieve this for a beginner in React? And how would I go about it?
const Search = () => {
let location = useLocation();
let navigate = useNavigate();
const handleKeyDown = (event) => {
if (event.key === 'Enter') {
if (location.pathname === '/') {
navigate('./List');
}
}
}
return (
<div className="searchbar-container">
<input className="searchbar" placeholder="get" onKeyDown={handleKeyDown}></input>
</div>
)
}
const Navbar = () => {
return (
<nav className='navigation'>
<div className='left-slot'>
<button>TITLE</button>
</div>
<div className='right-slot'>
<button>LINK</button>
<button>LINK</button>
</div>
</nav>
)
}
const Home = () => {
return (
<Search></Search>
)
}
function App() {
return (
<Router>
<Navbar></Navbar>
<Routes>
<Route exact path='/' element={<Home />} />
<Route path='/List' element={<List />} />
</Routes>
</Router>
);
}
CodePudding user response:
You can call the component on your NavBar and push the search string on the url (like params) or with the location state (but the first is better).
something like that :
if (event.key === 'Enter') {
if (location.pathname === '/') {
navigate(`./List/${searchValue}`);
}
}
and for the List page :
const {search} = useParams() // from router
also you need to add on your list route :
<Route path='/list/:search' element={<List />} />
Say me if it's good for you