What is Routing?
Routing in a web application refers to determining which component should be displayed based on the current URL. For example, you might want to display a homepage when the URL is /, an about page when the URL is /about, and so on.
Steps to Setting Up Routing
1. Install react-router-dom
First, you need to install the react-router-dom package, which provides the necessary tools for routing in React.
2. Basic Setup
Create a React application if you haven't already.
3. Set Up the Router in App.js
Let's set up the router in your App.js file.
App.js
4. Create the Components
Create the components that will be rendered for each route.
Home.js
About.js
NotFound.js
5. Navigation Links
Create a Navigation component to provide links for navigation.
Navigation.js
How Does It Work?
- Router: The BrowserRouter (aliased as Router) component wraps your application and enables routing.
- Route: The Route component defines a mapping between a URL path and a component. The exact prop ensures the route matches exactly.
- Switch: The Switch component renders the first child Route that matches the URL. If no route matches, the NotFound component is displayed.
- Link: The Link component is used to create navigation links. These links change the URL without causing a page to reload.
Run Your Application
Start your application by running.
Navigate to http://localhost:3000 in your browser. You should see the Home page. Click on the "About" link to navigate to the About page, and enter any other URL (like /XYZ) to see the NotFound page.
Summary
This article covered the basics of setting up routing in a React application using react-router-dom. By following these steps, you can create a multi-page application with navigation and different components rendered based on the URL. For more advanced routing features, refer to the react-router-dom documentation.