Home > OS >  React router is taking me to the same page
React router is taking me to the same page

Time:02-26

I have a nav bar that has Home and About links , I'm trying to make a router that goes to About page when I click on about link and goes to home when I click on Home link , but I don't know why either I click at home or about , It takes me to Home page

this is App.js file :

<Router>
<Box>
<Navbar />
<Home />
<Routes>
<Route exact path="/" component={Home}/>
<Route path="/about" component={AboutUs}/>
</Routes>
</Box>
</Router>

and this is Home.js file :

function Home() {
  return (
    <div>
    <FirstSection />
    <SecondSection />
    <ThirdSection />
    </div>
  )
}

and this is About file :

function AboutUs() {
  return (
    <div>AboutUs</div>
  )
}

and lastly this is the nav bar :

<a href="/">
            <MenuButton>
                Home
            </MenuButton>
            </a>
        </Menu>
        <Menu>
        <a href="/about">
            <MenuButton>
                About us 
            </MenuButton>
            </a>

CodePudding user response:

Try using the <Link /> component on the <NavBar /> component instead of <a> tags.

Thus your code should look like

<Menu>
    <Link to="/home">
        <MenuButton>
            Home
        </MenuButton>
    </Link>
</Menu>
<Menu>
     <Link to="/about">
         <MenuButton>
              About us 
         </MenuButton>
      </Link>
</Menu>

For more info about the <Link /> component you can read through the react-router docs.

CodePudding user response:

Try it:


 <Menu>
<Lint to="/">
  <MenuButton>
     Home
   </MenuButton>
 </Lint >
   </Menu>
   <Menu>
      <Link to="/about">
        <MenuButton>
           About us 
        </MenuButton>
      </Link >
   </Menu>

If your livestock router version is 6, you should do this:

import {
  BrowserRouter,
  Routes,
  Route,
} from "react-router-dom";

<BrowserRouter>
    <Routes>
      <Route path="/" element={<Home/>}>
        <Route path="/about" element={<AboutUs/>}>
        </Route>
      </Route>
    </Routes>
  </BrowserRouter>
  • Related