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>
);
![](https://appifybooks.com/wp-content/uploads/2024/01/Code_58TQWMZejg-1024x575.png)
After that, You can create some example page in the src/pages
![](https://appifybooks.com/wp-content/uploads/2024/01/Code_fXl0dYdLt2-1024x492.png)
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
![](https://appifybooks.com/wp-content/uploads/2024/01/Code_XGKqGMTl2w-1024x540.png)
Save All code and go To Browser, You can see Router is working, you can go to each page by clicking to link
![](https://appifybooks.com/wp-content/uploads/2024/01/chrome_uZUe5WUefG-1024x504.png)
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.