Home  >  Article  >  Web Front-end  >  How to Pass Props to Target Components in React Router\'s Link?

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 21:38:02739browse

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} />

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} />

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

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

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

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

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

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

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"}}} />

In the target component:

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

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!

Statement:
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