Home Web Front-end JS Tutorial Senior level: Routing with React Router

Senior level: Routing with React Router

Jul 18, 2024 pm 08:01 PM

Senior level: Routing with React Router

As a senior-level developer, it's crucial to have a comprehensive understanding of routing in React applications. React Router provides a robust solution for managing navigation and rendering of components based on URL paths. This guide covers the setup of React Router, essential components, and advanced techniques such as nested routes, dynamic routing, route parameters, and route guards.

Introduction to React Router

React Router is a powerful library for handling client-side routing in React applications. It allows for dynamic routing, nested routes, and conditional rendering based on the URL path.

Setting Up React Router

First, install React Router using npm or yarn:

1

npm install react-router-dom

Copy after login

or

1

yarn add react-router-dom

Copy after login

Route, Switch, Link, and NavLink Components

React Router provides several components to define routes and handle navigation.

Route Component

The Route component is used to define a path and associate it with a component.

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import React from 'react';

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

import Home from './Home';

import About from './About';

 

const App = () => {

  return (

    <Router>

      <Route path="/" exact component={Home} />

      <Route path="/about" component={About} />

    </Router>

  );

};

 

export default App;

Copy after login

Switch Component

The Switch component ensures that only one route is rendered at a time, matching the first route that fits.

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

import React from 'react';

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

import Home from './Home';

import About from './About';

import NotFound from './NotFound';

 

const App = () => {

  return (

    <Router>

      <Switch>

        <Route path="/" exact component={Home} />

        <Route path="/about" component={About} />

        <Route component={NotFound} />

      </Switch>

    </Router>

  );

};

 

export default App;

Copy after login

Link Component

The Link component creates navigational links, preventing full page reloads and preserving the single-page application experience.

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

import React from 'react';

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

import Home from './Home';

import About from './About';

 

const App = () => {

  return (

    <Router>

      <nav>

        <Link to="/">Home</Link>

        <Link to="/about">About</Link>

      </nav>

      <Route path="/" exact component={Home} />

      <Route path="/about" component={About} />

    </Router>

  );

};

 

export default App;

Copy after login

NavLink Component

The NavLink component is similar to Link but allows for styling based on the active route.

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

import React from 'react';

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

import Home from './Home';

import About from './About';

 

const App = () => {

  return (

    <Router>

      <nav>

        <NavLink exact to="/" activeClassName="active">

          Home

        </NavLink>

        <NavLink to="/about" activeClassName="active">

          About

        </NavLink>

      </nav>

      <Route path="/" exact component={Home} />

      <Route path="/about" component={About} />

    </Router>

  );

};

 

export default App;

Copy after login

Advanced Routing Techniques

Nested Routes

Nested routes allow you to create routes within other routes, which is useful for complex layouts with sub-navigation.

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

import React from 'react';

import { BrowserRouter as Router, Route, Switch, Link, useRouteMatch } from 'react-router-dom';

 

const Topic = ({ match }) => <h3>Requested Topic ID: {match.params.topicId}</h3>;

 

const Topics = () => {

  let { path, url } = useRouteMatch();

  return (

    <div>

      <h2>Topics</h2>

      <ul>

        <li>

          <Link to={`${url}/components`}>Components</Link>

        </li>

        <li>

          <Link to={`${url}/props-v-state`}>Props v. State</Link>

        </li>

      </ul>

      <Switch>

        <Route exact path={path}>

          <h3>Please select a topic.</h3>

        </Route>

        <Route path={`${path}/:topicId`} component={Topic} />

      </Switch>

    </div>

  );

};

 

const App = () => (

  <Router>

    <div>

      <ul>

        <li>

          <Link to="/">Home</Link>

        </li>

        <li>

          <Link to="/topics">Topics</Link>

        </li>

      </ul>

      <Switch>

        <Route exact path="/">

          <h2>Home</h2>

        </Route>

        <Route path="/topics" component={Topics} />

      </Switch>

    </div>

  </Router>

);

 

export default App;

Copy after login

Dynamic Routing

Dynamic routing allows creating routes based on dynamic parameters, useful for user profiles or product details.

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

import React from 'react';

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

 

const User = ({ match }) => <h3>User ID: {match.params.userId}</h3>;

 

const App = () => (

  <Router>

    <div>

      <ul>

        <li>

          <Link to="/user/1">User 1</Link>

        </li>

        <li>

          <Link to="/user/2">User 2</Link>

        </li>

      </ul>

      <Switch>

        <Route path="/user/:userId" component={User} />

      </Switch>

    </div>

  </Router>

);

 

export default App;

Copy after login

Route Parameters

Route parameters allow capturing values from the URL to be used in components.

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

import React from 'react';

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

 

const Product = ({ match }) => <h3>Product ID: {match.params.productId}</h3>;

 

const App = () => (

  <Router>

    <div>

      <ul>

        <li>

          <Link to="/product/101">Product 101</Link>

        </li>

        <li>

          <Link to="/product/202">Product 202</Link>

        </li>

      </ul>

      <Switch>

        <Route path="/product/:productId" component={Product} />

      </Switch>

    </div>

  </Router>

);

 

export default App;

Copy after login

Route Guards and Redirects

Protecting Routes

Route guards restrict access to certain routes based on conditions such as user authentication.

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

import React from 'react';

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

 

const isAuthenticated = false;

 

const PrivateRoute = ({ component: Component, ...rest }) => (

  <Route

    {...rest}

    render={(props) =>

      isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />

    }

  />

);

 

const Dashboard = () => <h3>Dashboard</h3>;

const Login = () => <h3>Login</h3>;

 

const App = () => (

  <Router>

    <div>

      <PrivateRoute path="/dashboard" component={Dashboard} />

      <Route path="/login" component={Login} />

    </div>

  </Router>

);

 

export default App;

Copy after login

Implementing Redirects in React Router

Redirects can navigate users to different routes programmatically.

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

import React from 'react';

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

 

const OldPage = () => <h3>Old Page (will redirect)</h3>;

const NewPage = () => <h3>New Page</h3>;

 

const App = () => (

  <Router>

    <Switch>

      <Route path="/old-page">

        <Redirect to="/new-page" />

      </Route>

      <Route path="/new-page" component={NewPage} />

    </Switch>

  </Router>

);

 

export default App;

Copy after login

In this example, visiting /old-page automatically redirects the user to /new-page.

Conclusion

Mastering routing with React Router is essential for building sophisticated and user-friendly React applications. Understanding how to set up routes, use core components, and implement advanced techniques such as nested routes, dynamic routing, route parameters, and route guards will enable you to create robust navigation systems. As a senior developer, these skills will help you design and implement scalable routing architectures in your React projects, ensuring a seamless user experience and maintainable codebase.

The above is the detailed content of Senior level: Routing with React Router. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Replace String Characters in JavaScript

jQuery Check if Date is Valid jQuery Check if Date is Valid Mar 01, 2025 am 08:51 AM

jQuery Check if Date is Valid

jQuery get element padding/margin jQuery get element padding/margin Mar 01, 2025 am 08:53 AM

jQuery get element padding/margin

10 Worth Checking Out jQuery Plugins 10 Worth Checking Out jQuery Plugins Mar 01, 2025 am 01:29 AM

10 Worth Checking Out jQuery Plugins

10 jQuery Accordions Tabs 10 jQuery Accordions Tabs Mar 01, 2025 am 01:34 AM

10 jQuery Accordions Tabs

HTTP Debugging with Node and http-console HTTP Debugging with Node and http-console Mar 01, 2025 am 01:37 AM

HTTP Debugging with Node and http-console

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

Custom Google Search API Setup Tutorial

jquery add scrollbar to div jquery add scrollbar to div Mar 01, 2025 am 01:30 AM

jquery add scrollbar to div

See all articles