Ad
How To Add One Component In Another Based On Event In React?
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>
);
}
Ad
Answer
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
Ad
source: stackoverflow.com
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad