Introduction
React JS has become one of the most popular frontend frameworks for web development. It allows developers to create complex and dynamic user interfaces with ease. Routing is an essential part of web development, and React Router is one such library that is used to manage routing in React applications.
In this article, we’ll cover the basics of routing in React JS using React Router. We’ll discuss how to get started with React Router, navigate between different components, pass props, handle nested routes, and handle errors.
Getting Started with React Router
Before we dive into the details of React Router, let’s start by installing React Router and setting up the basic components. React Router is available as a separate library, which we can install via the npm package manager.
npm install react-router-dom
The three main components that we use in React Router are Router, Route, and Routes. The Router component is the root component and is responsible for managing the application’s history and location. The Route component is used to define a new route and map it to a specific component. The Routes component is used to group Route components and ensures that at most one Route is rendered at a time.
Once we have installed React Router, we can import these components and use them in our application.
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={Home} />
<Route path="/about" element={About} />
<Route path="/contact" element={Contact} />
</Routes>
</Router>
);
}
In the above code, we’ve defined three routes: one for the Home component, one for the About component, and one for the Contact component. The exact keyword is used for the Home component to ensure that it only matches the home route ‘/’.
Navigating in React Router
Once we have set up our routes, we can use the Link component to navigate between them. Link is used in place of the traditional anchor tag to ensure that the page is not refreshed on navigation.
import { Link } from 'react-router-dom';
function App() {
return (
<Router>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
<Routes>
<Route path="/" element={Home} />
<Route path="/about" element={About} />
<Route path="/contact" element={Contact} />
</Routes>
</Router>
);
}
In the above code, we’ve added a navbar with three links to the different routes. When one of the links is clicked, the respective component will be rendered.
If we want to highlight the active link, we can use the NavLink component. NavLink is similar to Link but adds an active class when the link is active.
import { NavLink } from 'react-router-dom';
function App() {
return (
<Router>
<nav>
<ul>
<li>
<NavLink exact activeClassName="active" to="/">
Home
</NavLink>
</li>
<li>
<NavLink activeClassName="active" to="/about">
About
</NavLink>
</li>
<li>
<NavLink activeClassName="active" to="/contact">
Contact
</NavLink>
</li>
</ul>
</nav>
<Routes>
<Route path="/" element={Home} />
<Route path="/about" element={About} />
<Route path="/contact" element={Contact} />
</Routes>
</Router>
);
}
In the above code, we’ve used NavLink instead of Link and added the activeClassName prop to highlight the active link with the class ‘active’.
Redirecting in React Router
In some cases, we may want to redirect the user to a different route. This can be accomplished using the useNavigate hook.
import { Navigate } from 'react-router-dom';
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const navigation = useNavigate();
return (
<Router>
<nav>
<ul>
<li>
<NavLink exact activeClassName="active" to="/">
Home
</NavLink>
</li>
<li>
<NavLink activeClassName="active" to="/about">
About
</NavLink>
</li>
<li>
<NavLink activeClassName="active" to="/contact">
Contact
</NavLink>
</li>
</ul>
</nav>
<Routes>
<Route path="/" element={Home} />
<Route path="/about" element={About} />
<Route path="/contact" element={Contact} />
<Route path="/login">
{isLoggedIn ? <Navigate to="/"/> : <LoginForm />}
</Route>
</Routes>
</Router>
);
}
In the above code, we’ve added a new Route for the login page. If the user is already logged in, they will be redirected to the home page. Otherwise, the LoginForm component will be rendered.
Passing Props in React Router
In some cases, we may want to pass props to the component being rendered by the Route. This can be accomplished using the render method instead of the component prop.
function App() {
const [username, setUsername] = useState('');
return (
<Router>
<nav>
<ul>
<li>
<NavLink exact activeClassName="active" to="/">
Home
</NavLink>
</li>
<li>
<NavLink activeClassName="active" to="/about">
About
</NavLink>
</li>
<li>
<NavLink activeClassName="active" to="/contact">
Contact
</NavLink>
</li>
</ul>
</nav>
<Routes>
<Route path="/" element={Home} />
<Route path="/about" element={About} />
<Route
path="/profile"
render={(props) => <Profile {...props} username={username} />}
/>
<Route path="/contact" element={Contact} />
</Routes>
</Router>
);
}
In the above code, we’ve added a new Route for the Profile page and passed the username prop to the Profile component using the render method.
file component and pass the history object to the component as a prop.
Programmatic Navigation in React Router
In addition to navigating using links and buttons, we can also navigate programmatically using the history object.
The history object is available to components rendered by a Route. It allows us to navigate, go back, and forward.
import { useNavigate } from 'react-router-dom';
function LoginForm() {
const navigation = useNavigate();
const handleSubmit = (event) => {
event.preventDefault();
navigation.navigate('/');
};
return (
<div>
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<label>
Username
<input type="text" />
</label>
<label>
Password
<input type="password" />
</label>
<button type="submit">Submit</button>
</form>
</div>
);
}
In the above code, we’ve used the useHistory hook to get the history object and used history.push to navigate to the home route on form submission.
Nested Routes in React Router
Nested routes are used when one component contains other components that have their own routes. To create nested routes, we need to first define the parent Route and then nest the child routes within it.
function App() {
return (
<Router>
<nav>
<ul>
<li>
<NavLink exact activeClassName="active" to="/">
Home
</NavLink>
</li>
<li>
<NavLink activeClassName="active" to="/about">
About
</NavLink>
</li>
<li>
<NavLink activeClassName="active" to="/contact">
Contact
</NavLink>
</li>
</ul>
</nav>
<Routes>
<Route path="/" element={Home} />
<Route path="/about" element={About} />
<Route path="/contact" element={Contact} />
<Route path="/users/:id" element={User} />
<Route path="/users" element={Users} />
</Routes>
</Router>
);
}
function Users() {
return (
<div>
<h1Users</h1>
<p>Select a user</p>
<ul>
<li>
<Link to="/users/1">User 1</Link>
</li>
<li>
<Link to="/users/2">User 2</Link>
</li>
<li>
<Link to="/users/3">User 3</Link>
</li>
</ul>
</div>
);
}
function User(props) {
const { id } = props.match.params;
return (
<div>
<h1>User {id}</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
</div>
);
}
In the above code, we have nested routes for the Users component. The Users component renders a list of users with links to their respective pages. The User component is rendered when a user link is clicked, and the user’s id is passed as a prop.
Handling 404 Errors in React Router
In some cases, we may want to handle 404 errors when a user navigates to a non-existent route. This can be accomplished using a wildcard Route that is defined at the end of all other Routes.
function App() {
return (
<Router>
<nav>
<ul>
<li>
<NavLink exact activeClassName="active" to="/">
Home
</NavLink>
</li>
<li>
<NavLink activeClassName="active" to="/about">
About
</NavLink>
</li>
<li>
<NavLink activeClassName="active" to="/contact">
Contact
</NavLink>
</li>
</ul>
</nav>
<Routes>
<Route path="/" element={Home} />
<Route path="/about" element={About} />
<Route path="/contact" element={Contact} />
<Route path="/users/:id" element={User} />
<Route path="/users" element={Users} />
<Route element={NotFound} />
</Routes>
</Router>
);
}
function NotFound() {
return (
<div>
<h1>404 Not Found</h1>
<p>The page you are looking for does not exist.</p>
</div>
);
}
In the above code, we’ve added a NotFound component to handle 404 errors. The Route component with no path prop matches any route that hasn’t been matched yet and renders the NotFound component.
Conclusion
React Router is an essential tool for managing routing in React JS applications. With React Router, we can easily create nested routes, handle 404 errors, pass props, and navigate programmatically. By following the basics outlined in this article, you can easily get started with React Router and create dynamic and interactive web applications.
What Is JSX and how to use it.
Introduction As a web developer, I’m always on the lookout for new tools and technologies that can help me write better code faster. One tool that has caught my attention lately is Typescript JSX. In this article, I’m going to share my experience learning Typescript JSX and the benefits it has brought to my development […]
React JS vs Svelte
Introduction In the world of web development, there are many frameworks available for use. Two of the most popular frameworks are React JS and Svelte. React JS is an open-source JavaScript library developed by Facebook while Svelte is a relatively new framework developed by Rich Harris in 2016. In this article, we will compare React […]
How To Use Google Login With React
As a developer, I cannot stress enough the importance of creating a seamless user experience when it comes to authentication. One of the most popular and convenient ways to allow users to authenticate is by using Google Login. In this article, we’ll explore how to use Google Login with React. Before we delve deep into […]
React JS vs Angular: A Comprehensive Guide
Introduction Web development has come a long way since the earlier days of static HTML pages. Web applications have become more dynamic, interactive and more like native applications. This transformation has brought about the rise of JavaScript frameworks and libraries, which have become essential in building web applications. However, choosing between these libraries or frameworks […]
Create Forms In React Using React Hook Form
Introduction React Hook Form is a popular tool used in building forms in React.js. It is a performant library that simplifies the process of building forms by reducing boilerplate code and providing convenient features. This article is aimed at introducing the basic concepts of React Hook Form and how to use it to create forms […]
React JS vs Vue: A Comprehensive Guide
Introduction ReactJS and Vue are two of the most popular JavaScript libraries used to develop dynamic user interfaces. These libraries have gained widespread popularity due to their flexibility, efficiency, and ease of use. ReactJS was developed by Facebook, and Vue was created by Evan You. In this article, we are going to evaluate and compare […]