Home > Web Front-end > JS Tutorial > How Can I Pass Data Between Pages Using React Router?

How Can I Pass Data Between Pages Using React Router?

Mary-Kate Olsen
Release: 2024-12-30 06:26:10
Original
309 people have browsed it

How Can I Pass Data Between Pages Using React Router?

Passing Data Between React Router Pages

Overview

React Router is a powerful library for implementing navigation in React applications. It allows you to define routes and handle page transitions seamlessly. One common use case is passing data between pages for display or further processing.

Solution:

Option 1: Route State

With React Router v6, you can use the state property of the Link or Navigate components to pass data when navigating. This data is accessible through the location object on the destination page.

Option 2: URL Path

Another option is to incorporate data into the URL path using the : notation. The data can be retrieved from the match props on the destination page.

Option 3: URL Query String

Similar to using the URL path, you can append data to the URL query string using the ? symbol. This data can be accessed through the useSearchParams hook or the location object's search property on the destination page.

Example:

Consider a scenario where you want to navigate from a list of users to a user details page.

// User List Page
import React, { Component } from "react";

export default class User extends Component {
  render() {
    return (
      {this.props.users.map(user => (
        <Link key={user.id} to={`/user/${user.id}`}>
          {user.name}
        </Link>
      ))}
    );
  }
}
Copy after login
// User Details Page
import React from "react";
import { useParams } from "react-router-dom";

export default function UserDetails() {
  const { id } = useParams();
  return (
    {id}
  );
}
Copy after login

In this example, when a user clicks on a user's name, they are navigated to the UserDetails page, which receives the user's ID through the URL path.

The above is the detailed content of How Can I Pass Data Between Pages Using React Router?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template