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

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 
  <React.StrictMode> // <-- add this 
      <App />
    </BrowserRouter> // <-- add this 

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


function Home() {
    return (

export default Home;


function Contact() {
    return (

export default Contact;


function About() {
    return (

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

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

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

Your email address will not be published. Required fields are marked *

Scroll to Top