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.
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.
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.
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.
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> ))} ); } }
// User Details Page import React from "react"; import { useParams } from "react-router-dom"; export default function UserDetails() { const { id } = useParams(); return ( {id} ); }
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!