Mark As Completed Discussion

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:

  1. Import the necessary components from the react-router-dom package, such as BrowserRouter, Route, and Link.

  2. Wrap your application component with the BrowserRouter component. This component provides the routing functionality for your application.

  3. Define routes using the Route component. Each Route component 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:

JAVASCRIPT
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!

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment