Client-side routing is a fundamental concept when building single-page applications (SPAs) with React. It allows you to create a smooth and seamless user experience by changing the content of your web application without triggering a full page reload. In this tutorial, we’ll explore how to implement client-side routing in a React application using the popular libraries React Router and Reach Router.
Prerequisites:
- Basic knowledge of React.
- Node.js and npm (Node Package Manager) installed on your computer.
- A code editor of your choice (e.g., Visual Studio Code).
1. Project Setup
Start by creating a new React application if you don’t already have one. You can use Create React App or set up your project from scratch.
npx create-react-app react-router-tutorial cd react-router-tutorial
2. Installing React Router or Reach Router
You have two popular options for client-side routing in React: React Router and Reach Router. Choose the one that best suits your project’s needs. For this tutorial, we’ll use React Router.
To install React Router, run the following command:
npm install react-router-dom
3. Creating Routes
In your React project, you’ll need to set up routes. Create a component for each route you want to define. For example, if you have two routes: Home and About, create components for both.
// src/components/Home.js import React from 'react'; function Home() { return <div>Home Page</div>; } export default Home;
// src/components/About.js import React from 'react'; function About() { return <div>About Page</div>; } export default About;
4. Navigation
Now, let’s set up navigation using the react-router-dom
library. Create a navigation bar with links to your routes:
// src/components/Navbar.js import React from 'react'; import { Link } from 'react-router-dom'; function Navbar() { return ( <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> </nav> ); } export default Navbar;
5. Route Parameters
You can also pass parameters to routes. For example, to create a dynamic route for displaying user profiles:
// src/components/UserProfile.js import React from 'react'; import { useParams } from 'react-router-dom'; function UserProfile() { const { username } = useParams(); return <div>User Profile Page for {username}</div>; } export default UserProfile;
In your route configuration, use :paramName
to define dynamic segments:
// src/App.js import React from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Home from './components/Home'; import About from './components/About'; import Navbar from './components/Navbar'; import UserProfile from './components/UserProfile'; function App() { return ( <Router> <Navbar /> <Switch> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> <Route path="/profile/:username" component={UserProfile} /> </Switch> </Router> ); } export default App;
6. Nested Routes
You can nest routes to create complex layouts. For example, you can have a Dashboard component with its own routes:
// src/components/Dashboard.js import React from 'react'; import { Route, Switch, Link, useRouteMatch } from 'react-router-dom'; function Dashboard() { let { path, url } = useRouteMatch(); return ( <div> <h2>Dashboard</h2> <ul> <li> <Link to={`${url}/profile`}>Profile</Link> </li> <li> <Link to={`${url}/settings`}>Settings</Link> </li> </ul> <Switch> <Route path={`${path}/profile`}>Profile Component</Route> <Route path={`${path}/settings`}>Settings Component</Route> </Switch> </div> ); } export default Dashboard;
7. Redirects
To redirect users from one route to another, use the Redirect
component:
// src/components/RedirectComponent.js import React from 'react'; import { Redirect } from 'react-router-dom'; function RedirectComponent() { return <Redirect to="/about" />; } export default RedirectComponent;
8. 404 Page
To handle routes that don’t match any defined routes, create a 404 page:
// src/components/NotFound.js import React from 'react'; function NotFound() { return <div>404 - Not Found</div>; } export default NotFound;
Then, include it in your route configuration as the last route:
<Switch> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> <Route path="/profile/:username" component={UserProfile} /> <Route path="/dashboard" component={Dashboard} /> <Route path="/redirect" component={RedirectComponent} /> <Route path="*" component={NotFound} /> </Switch>
9. Programmatic Navigation
You can also navigate programmatically using the useHistory
hook:
import { useHistory } from 'react-router-dom'; function MyComponent() { const history = useHistory(); const handleClick = () => { history.push('/new-route'); }; return <button onClick={handleClick}>Go to New Route</button>; }
10. Conclusion
In this tutorial, you’ve learned how to implement client-side routing in a React application using React Router. You can achieve similar results with Reach Router, and the choice between the two largely depends on your project’s requirements.
Client-side routing enhances the user experience by allowing you to create dynamic and responsive web applications without full-page reloads. With the concepts covered in this tutorial, you can create complex routing structures for your React projects.