Home > AI > Frontend > react-router-dom >

BrowserRouter

Step 1: install

npm i react-router-dom

Step 2: create relevant files

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import Nav from './Nav';
import Home from './Home';
import About from './About';
import Shop from './Shop';


ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <Nav />
      <Switch>
        <Route path='/' exact>{Home}</Route>
        <Route path='/about'>{About}</Route>
        <Route path='/shop'>{Shop}</Route>
      </Switch>
    </BrowserRouter>
   
    
  </React.StrictMode>,
  document.getElementById('root')
);


// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Nav.js

import React from 'react'
import './Nav.scss'
import {Link} from 'react-router-dom'
import About from './About'
import Shop from './Shop'


export default function Nav() {
    return (
        <nav>
            <h3>Logo</h3>
            <ul>
                <Link to="/about">About</Link>
                <Link to="/shop">Shop</Link>
            </ul>
        </nav>
    )
}

Home.js

import React from 'react'

export default function Home() {
    return (
        <div>
            Home Page
        </div>
    )
}


About.js

import React from 'react'

export default function About() {
    return (
        <div>
            About Page
        </div>
    )
}

Shop.js

import React from 'react'

export default function Shop() {
    return (
        <div>
            Shop Page
        </div>
    )
}

This video is helpful

https://www.youtube.com/watch?v=Law7wfdg_ls

Leave a Reply