Home >Web Front-end >JS Tutorial >How Can I Pass Props in Links Using React Router?

How Can I Pass Props in Links Using React Router?

DDD
DDDOriginal
2024-11-01 03:33:27482browse

How Can I Pass Props in Links Using React Router?

Pass Props in Link in React-Router

When using the component in React-Router, it is possible to pass properties to the new view. To do this, use the to property of and pass an object with the desired properties. For example:

<code class="js"><Link to={{ pathname: '/ideas', query: { testvalue: 'hello' } }}>Create Idea</Link></code>

In the destination view, access the passed properties using the following pattern:

<code class="js">render() {
    console.log(this.props.match.params.testvalue, this.props.location.query.backurl)
    return <span>{testvalue} {backurl}</span>    
}</code>

note: the above syntax is now out dated

In updated Functional Components using hooks:

<code class="js">const CreatedIdeaView = () => {
    const { testvalue } = useParams();
    const { query, search } = useLocation(); 
    console.log(testvalue, query.backUrl, new URLSearchParams(search).get('backUrl'))
    return <span>{testvalue} {backurl}</span>    
}</code>

Further Considerations

  • Ensure that the destination route has a matching path defined to receive the passed property. In this example, the route should be defined as follows:
<code class="js"><Route name="ideas" path="/:testvalue" handler={CreateIdeaView} /></code>
  • The Link component used in React-Router has been updated in recent versions. The syntax for passing properties may differ depending on the version being used.

The above is the detailed content of How Can I Pass Props in Links Using React Router?. 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