- Install the react router in your project
npm i react-router-dom
- Then import the react router in your App.js
import React from "react"; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; export default function App() { return ( <Router> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/users">Users</Link> </li> </ul> </nav> {/* A <Switch> looks through its children <Route>s and renders the first one that matches the current URL. */} <Switch> <Route path="/about"> <About /> </Route> <Route path="/users"> <Users /> </Route> <Route path="/"> <Home /> </Route> </Switch> </div> </Router> ); } function Home() { return <h2>Home</h2>; } function About() { return <h2>About</h2>; } function Users() { return <h2>Users</h2>; }
- In place of switch we now using Routes and in Route tag we use the element attribute to get the desired element to be rendered
Code
// import './App.css'; import Drp from './components/dropdown/Drp'; import "@material-tailwind/react/tailwind.css"; import Navbar from './components/dropdown/Navbar'; // import Alert from './components/Alerts/Alert'; import PageOne from './components/Page1/PageOne'; // import { Router } from 'react-router-dom'; import {BrowserRouter as Router,Routes,Route,Link, useRoutes} from "react-router-dom"; import Page2 from './components/Page2/Page2'; function App() { // useRoutes() return ( <div className="App bg-gray-200 h-full w-full pb-[200px]"> <header className="App-header"> {/* <PageOne/> <Page2/> */} {/* */} <Router> {/* We have to provide the Navbar inside router so that router do not it can */} <Navbar /> <Routes> <Route path="/about" element={<Page2/>} /> <Route path="/" element={<PageOne/>} /> </Routes> </Router> {/* */} </header> </div> ); } export default App;
NavLink
it is the ano
redirection
Page not Found
When no route is found then we can render a not found page
We have to give this path at the end so that if no path above this is matched then it will render the no found component
we have to give “ * “ in the path section