💡 Learn from AI

React Fundamentals

React Router

React Router

React Router is a library for managing navigation in a React application. It allows developers to create routes that map to specific components or pages, making it easy to build single-page applications with multiple views. React Router uses a declarative syntax that allows developers to define routes using JSX, making it easy to read and understand the structure of the application.

Basic Usage

React Router provides several components that allow developers to create routes in their application. The most basic component is the BrowserRouter, which should be added to the root of the application. Inside the BrowserRouter, developers can define routes using the Route component. For example, the following code defines a route that maps to the Home component:

import { BrowserRouter, Route } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Route path='/' component={Home} />
    </BrowserRouter>
  );
}

In this example, the path property defines the URL path that should map to the Home component. When the URL of the application matches the path, the Home component will be rendered.

Nested Routes

React Router also allows developers to create nested routes, which can be useful for creating complex applications. To create a nested route, developers can define a Switch component that contains multiple Route components. For example, the following code defines a nested route that maps to the Profile component:

import { BrowserRouter, Route, Switch } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path='/' component={Home} />
        <Route path='/profile' component={Profile} />
      </Switch>
    </BrowserRouter>
  );
}

In this example, the exact property is used to ensure that the Home component is only rendered when the URL path matches exactly. The Profile component is nested inside the Switch component, which allows React Router to render the correct component based on the URL path.

Further Reading

React Router is a powerful library that provides many more features than are covered in this lesson. Developers can learn more by reading the official documentation at

https://reactrouter.com/web/guides/quick-start

.

Take quiz (4 questions)

Previous unit

React Hooks

All courses were automatically generated using OpenAI's GPT-3. Your feedback helps us improve as we cannot manually review every course. Thank you!