Address
304 North Cardinal St.
Dorchester Center, MA 02124
Work Hours
Monday to Friday: 7AM - 7PM
Weekend: 10AM - 5PM
React Router is a popular routing library for React applications. It allows you to handle navigation and routing in a declarative way, enabling you to create single-page applications with multiple views.
To set up client-side routing using React Router, you can use the react-router-dom
package which is used to provide a set of components and utilities for managing client-side routing in your React application.
npx create-react-app <project_name>
npx create-react-app@latest --typescript <project_name>
cd <project_name>
code .
npm start
First, you need to install React router using
npm install react-router-dom
or
yarn add react-router-dom
BrowserRouter
, Routes
, Route
and Link
to your App.js file or where you want to create your Navbar.<strong>pages</strong>
directory in src directory, and then create 3 file Home.js
, About.js
and Contact.js
.import React from "react";
function Home() {
return <div>This is Home Page</div>;
}
export default Home;
Once all the files are created, let’s move to create Routes.
In the App.js file first, we need to define the Links of our Navbar, these Links define the path that will be triggered once these are clicked, and the path defined in to=”” will be displayed in the browser’s address bar, to create routes use the following code.
<BrowserRouter>
, otherwise, it will throw an error.App.js
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
function App() {
return (
<BrowserRouter>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
</div>
</BrowserRouter>
);
}
export default App;
App.js
import React from "react";
import { Link, BrowserRouter as Router, Routes, Route } from "react-router-dom";
import HookState from "../class7/useState";
import HookEffect from "../class7/useEffect";
import Parent from "../class8/props";
function Nav() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
</div>
<Routes>
<Route path="/" Component={Parent} />
<Route path="/about" Component={HookState} />
<Route path="/contact" Component={HookEffect} />
</Routes>
</Router>
);
}
export default Nav;
Import Home from './pages/Home'
.That’s all to create routes in a ReactJS project. I hope it will be a quite useful tutorial to understand how to use React Router, how routes are created as well as how it works.
Also, check out React Component in 5 easy steps. If your want to learn more about ReactJS, you can follow all the ReactJS tutorials starting from “Introduction to React” on devcribe.com. Happy Coding!