Basic Routing
One of the key features of React Router is the ability to create routes and render components based on the URL. By defining different routes, you can control what components are rendered in different parts of your application.
To create routes in React Router, you need to:
Import the necessary components from the
react-router-dompackage, such asBrowserRouter,Route, andLink.Wrap your application component with the
BrowserRoutercomponent. This component provides the routing functionality for your application.Define routes using the
Routecomponent. EachRoutecomponent specifies a path and the component to render when that path matches the current URL.
For example, let's say you have a React application with two components: Home and About. To create routes for these components, you can use the following code:
1import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
2
3function App() {
4 return (
5 <Router>
6 <div>
7 <Route exact path="/" component={Home} />
8 <Route path="/about" component={About} />
9 </div>
10 </Router>
11 );
12}In this code snippet, we import the necessary components from react-router-dom, and then define two routes: one for the / path which renders the Home component, and one for the /about path which renders the About component.
With these routes defined, when the user navigates to /, the Home component will be rendered, and when they navigate to /about, the About component will be rendered.
This is a basic example of how to create routes and render components based on the URL in React Router. By defining different routes and components, you can build complex applications with multiple pages and navigation.
Now try implementing this code snippet in your own React project and see how routing works in practice!
xxxxxxxxxx// Import React Router componentsimport { BrowserRouter as Router, Route, Link } from 'react-router-dom';function App() { return ( <Router> <div> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </div> </Router> );}


