Skip to content
Advertisement

Beginner to React and Using React Router Dom v6 to navigate between pages

I’m struggling to navigate between different pages in react router I have my ReactDom.render() as follows:

ReactDOM.render((
  <BrowserRouter>
    <App/>
  </BrowserRouter>),
  document.getElementById('root'))
  

Here I have App.js with just my home and a second page (Park). If I place outside the tags the navbar is visible, but when inside the tags the navbar isn’t visible anymore.

function App() {
  
  const classes = styles();
  return (
    <>
      <Router>
        <NavBar />

        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/park_your_car" element={<Park />} />

        </Routes>
      </Router>
    </>
  );
}

export default App;

Then I placed my links inside my NavBar.js

function NavBar() {
    const classes = styles()
    return (
        <div>
        
        <Toolbar position = "sticky" color="rgba(255, 215, 0)" className={classes.bar}>
        <img src={logo} className={classes.logo}/>
        
        <Typography variant="h6" className={classes.menuItem}>
            
                <Link to="/"><b>Home</b> </Link>
            
        </Typography>
        <Typography variant="h6" className={classes.menuItem}>
            
                <Link to="/park_your_car"><b>Park Your Car</b></Link>
            
        </Typography>
        <Typography variant="h6" className={classes.menuItem}>
            
                <Link className="menuItem" to="/find_your_car"><b>Find Your Car</b></Link>
            
        </Typography>
        <Typography variant="h6" className={classes.menuItem}>
            
                <Link className="menuItem" to="/exit_from_lot"><b>Exit Lot</b></Link>
            
        </Typography>
        <CustomButton txt="Contact Us" />        
        </Toolbar>
        </div>
    )
}

Advertisement

Answer

You should remove <Router> tag and take out <Navbar> from the <Routes>

function App() {
  
  const classes = styles();
  return (
    <>
        <NavBar />

        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/park_your_car" element={<Park />} />
        </Routes>
    </>
  );
}

Why you should remove <Router> from App?

Because here, in index.js, you are already using BrowserRouter

import { BrowserRouter } from 'react-router-dom';

ReactDOM.render((
  <BrowserRouter>
    <App/>
  </BrowserRouter>),
  document.getElementById('root'))
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement