skip to Main Content

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


  1. You need to add BrowserRouter in your entry point .js/.tsx file.

    If you’re using npx create-react-app . then import BrowserRouter in index.js

    import { BrowserRouter } from "react-router-dom";
    .
    . // Other Imports..
    .
    
    <React.StrictMode>
        <BrowserRouter>
          <App />
        </BrowserRouter>
      </React.StrictMode>
    

    After that in your App component you need to use <Routes> & <Route>.

    and All Set!

    Login or Signup to reply.
  2. 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:

    import React from 'react';
    import { Link, useLocation } from 'react-router-dom';
    
    const Navigation = ({ history }) => {
      const location = useLocation();
    
      // You can use the `Link` component and `useLocation` hook here.
    
      return (
        <nav>
          <ul>
            <li>
              <Link to="/home">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            {/* Additional navigation items */}
          </ul>
        </nav>
      );
    };
    
    export default Navigation;
    

    In your main project where you use the Navigation component, make sure you wrap your entire application (App.js) with the BrowserRouter

    import React from 'react';
    import { BrowserRouter, Route } from 'react-router-dom';
    import Navigation from './Navigation';
    import Home from './Home';
    import About from './About';
    
    const App = () => {
      return (
        <BrowserRouter>
          <Navigation />
          <Route path="/home" component={Home} />
          <Route path="/about" component={About} />
          {/* Additional routes */}
        </BrowserRouter>
      );
    };
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search