To add React Router in your application, run this in the terminal from the root directory of the application:
npm i react-router-dom@latest
once installed, check out the example code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
import React from 'react'; import ReactDOM from 'react-dom/client'; import { BrowserRouter, Routes, Route,Link,Outlet} from 'react-router-dom'; function Page1() { return ( <div>Page 1</div> ) } function Page2() { return ( <div>Page 2</div> ) } function Page3() { return ( <div>Page 3</div> ) } function Layout() { return ( <> <nav> <ul> <li> <Link to="/">Link1</Link> </li> <li> <Link to="/1">Link2</Link> </li> <li> <Link to="/2">Link3</Link> </li> </ul> </nav> <Outlet /> </> ) } //App function component function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Layout />}> <Route index element={<Page1 />} /> <Route path="1" element={<Page2 />} /> <Route path="2" element={<Page3 />} /> </Route> </Routes> </BrowserRouter> ); } const root = ReactDOM.createRoot(document.getElementById("root")); //creating a root React component in your application root.render(<App />) // rendering React components into a DOM node. |
Output;
