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

How Can I Pass Props in Links Using React Router?

DDD
Release: 2024-11-01 03:33:27
Original
374 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login
  • 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!

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
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!