How to add Routers to the React Js app

In this previous post, I have introduce how About React Js and Create a simple React js app. As you can see it only have a page after crate new app. so In this post, I will introduce how to add Routers to the React Js.

To add routers to app, you need install react-router-dom, you can read more about it on the site https://reactrouter.com/en/main

npm install react-router-dom

After install react-router-dom, You need add <BrowserRouter > to the index.js file

// other 
import { BrowserRouter } from 'react-router-dom';
// other import 
root.render(
  <React.StrictMode> // <-- add this 
    <BrowserRouter>
      <App />
    </BrowserRouter> // <-- add this 
  </React.StrictMode>
);

After that, You can create some example page in the src/pages

src/pages/Home.jsx

function Home() {
    return (
        <h1>Home</h1>
    )
}

export default Home;

src/pages/Contact.jsx

function Contact() {
    return (
        <h1>Contact</h1>
    )
}

export default Contact;

src/pages/About.jsx

function About() {
    return (
        <h1>About</h1>
    )
}

export default About;

After create page, You need edit file src/app.js to add routers to the app, The first, you need import react-router-dom to the app

import { Routes, Route, Link } from 'react-router-dom'

Next step, You need import Pages Home, Contact, About to the src/App.js

import HomePage from './pages/Home';
import ContactPage from './pages/Contact';
import AboutPage from './pages/About';

After import page, You need create link and apply router to each page

     <nav>
        <ul>
          <li><Link to='/'>Home</Link></li>
          <li><Link to='/contact'>Contact</Link></li>
          <li><Link to='/about'>About</Link></li>
        </ul>
      </nav>
      <Routes>
        <Route path='/' element={<HomePage />} />
        <Route path='/contact' element={<ContactPage />} />
        <Route path='/about' element={<AboutPage />} />
      </Routes>

You can see full code in src/App.js

Save All code and go To Browser, You can see Router is working, you can go to each page by clicking to link

Conclusion: As you know each app or website will have multi pages, so you can use react routers to add 2 or more pages to the app.

Leave a Comment

Scroll to Top