Home > Web Front-end > JS Tutorial > body text

How to Pass Props to Target Components in React Router\'s Link?

Linda Hamilton
Release: 2024-10-31 21:38:02
Original
736 people have browsed it

How to Pass Props to Target Components in React Router's Link?

Pass Props in Link React-Router

React-Router's Link component allows for passing properties to target components. However, it's crucial to ensure proper route configuration to facilitate data transfer.

The issue arises when the route path does not match the intended property retrieval. In the provided code, the for the target component lacks a corresponding path:

<Route name="ideas" handler={CreateIdeaView} />
Copy after login

To resolve the issue and pass properties through the link, specify the path in the route configuration, ensuring it aligns with the parameters in the component:

<Route name="ideas" path="/:testvalue" handler={CreateIdeaView} />
Copy after login

The :testvalue placeholder parameter corresponds to the property passed in the :

<Link to="ideas" params={{ testvalue: "hello" }} />
Copy after login

Properties can now be accessed in the target component's render method:

render: function() {
  console.log(this.props.match.params.testvalue); // logs "hello"
}
Copy after login

Using hooks in functional components, you can access props like this:

const CreatedIdeaView = () => {
  const { testvalue } = useParams();
  console.log(testvalue); // logs "hello"
}
Copy after login

Alternatively, if you need to pass query parameters instead of path parameters, you can use it like this:

<Link to={{pathname: '/ideas', query: {testvalue: "hello"}}} />
Copy after login

In the target component:

componentDidMount() {
    console.log(this.props.location.query.testvalue) // logs "hello"
}
Copy after login

The above is the detailed content of How to Pass Props to Target Components in React Router\'s Link?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!