Home > Software engineering >  How to recognize when you're on that particular path using react-router-dom
How to recognize when you're on that particular path using react-router-dom

Time:08-16

I am using React router to navigate to different pages in my react app. In my footer, I have a link to a /about path. When I click that link it takes me to localhost:3000/about. However, when I click it again it takes me to localhost:3000/about/about. How do I avoid this? Below are my routes:

function App() {
  return (
    <Router>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="about" element={<About />} />
        <Route path="privacy" element={<Privacy />} />
        <Route path="templates" element={<Templates />} />
        <Route path="template-one" element={<TemplateOne />} />
        <Route path="template-two" element={<TemplateTwo />} />
        <Route path="contact" element={<Contact />} />
      </Routes>
    </Router>
  );
}

Footer:

const Footer = () => {
  return (
    <footer className={classes.footer}>
        <div className={classes.footerLinks}>
          <h2>Company</h2>
          <Link to="about" exact>
            About
          </Link>
          <Link to="privacy" exact>
            Privacy
          </Link>
          <Link to="/">Expectations</Link>
        </div>
    </footer>
  );
};

CodePudding user response:

You can try adding /asterisk (/*) in each route path.

<Route path="about/*" element={<About />} />

CodePudding user response:

Use / on your link

<Link to="/about">About</Link>

And if you are on sub level, Here is a question that answers the problem of switching only the last path in the endpoint. As the answer shows, you can use useLocation hook to know about the current location you are on.

  • Related