There is a navigation and search component in a separate npm package. These components are imported into the project in which react-router-dom is installed. I would like to use a component from react-router-dom called Link in the navigation component, as well as useLocation hooks, etc.
At the moment, I have to pass all the necessary parameters from the components to the project and route it already in the project.
The components require a BrowserRouter to work, it would be a bad way to put a BrowserRouter in each component, since they start multiplying and, moreover, do not pass the necessary data to the main BrowserRouter located in the project itself.
2
Answers
You need to add
BrowserRouter
in your entry point.js/.tsx
file.If you’re using
npx create-react-app .
then importBrowserRouter
inindex.js
After that in your
App
component you need to use<Routes>
&<Route>
.and All Set!
Pass history as a prop to the Navigation Component
You can pass the history object from the react-router-dom to the Navigation component as a prop. This way, you can use the Link component and useLocation hook inside the Navigation component without needing to wrap it with another BrowserRouter. Here’s an example:
In your main project where you use the Navigation component, make sure you wrap your entire application (App.js) with the BrowserRouter