Mark As Completed Discussion

React Router

Implementing client-side routing in React

To implement client-side routing in React, we can use the React Router library. React Router is a popular routing library for React that allows us to handle navigation and routing within a React application.

First, we need to install React Router using npm or yarn:

SNIPPET
1// npm
2npm install react-router-dom
3
4// yarn
5yarn add react-router-dom

Once installed, we can import the necessary components from React Router and use them in our application.

For example, to create a simple navigation bar with two links:

JAVASCRIPT
1import { BrowserRouter as Router, Link, Route } from 'react-router-dom';
2
3function App() {
4  return (
5    <Router>
6      <div>
7        <nav>
8          <ul>
9            <li>
10              <Link to='/'>Home</Link>
11            </li>
12            <li>
13              <Link to='/about'>About</Link>
14            </li>
15          </ul>
16        </nav>
17
18        <Route exact path='/' component={Home} />
19        <Route path='/about' component={About} />
20      </div>
21    </Router>
22  );
23}
24
25function Home() {
26  return <h1>Home</h1>;
27}
28
29function About() {
30  return <h1>About</h1>;
31}

In this example, we're using the BrowserRouter component from React Router as the root component and defining the routes using the Route component.

The Link component is used to create the navigation links. When a link is clicked, the corresponding route component is rendered.

The exact attribute in the Route component ensures that only the specified path is matched exactly.

With React Router, we can easily implement client-side routing in our React application.

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