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

How to Pass Props in Link with React-Router?

Susan Sarandon
Release: 2024-11-01 13:20:29
Original
816 people have browsed it

How to Pass Props in Link with React-Router?

Passing Props in Link React-Router

React-Router's Link component allows for passing data between components. To do so, define a parameter in the to prop of the Link, and the value for that parameter can be accessed in the linked component using this.props.

Issue:

The provided code failed to pass props to the linked component because the route path was missing from the definition.

Solution:

Add the path parameter to the definition:

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

Passing Data using Location:

When using react-router v4/v5, data can be passed through the location object:

Link (Query):

<Link to={{pathname: '/', query: {backUrl: 'theLinkData'}}} />
Copy after login

Link (Search):

<Link to={{pathname: '/', search: '?backUrl=theLinkData'}} />
Copy after login

Accessing Data (Functional Component):

const CreatedIdeaView = () => {
  const { query, search } = useLocation();
  console.log(query.backUrl, new URLSearchParams(search).get('backUrl'));
};
Copy after login

Accessing Data (Class Component):

class CreateIdeaView extends React.Component {
  render() {
    console.log(this.props.location.query.backUrl);
    return <div>{this.props.location.query.backUrl}</div>;
  }
}
Copy after login

Example:

class App extends React.Component {
  render() {
    return (
      <div>
        <Link to={{pathname: '/ideas', query: {foo: 'bar'}}} />
        <RouteHandler />
      </div>
    );
  }
}
Copy after login
class Ideas extends React.Component {
  render() {
    const { match, location } = this.props;
    console.log('props form link', this.props);
    return <p>{location.query.foo}</p>;
  }
}
Copy after login

The above is the detailed content of How to Pass Props in Link with 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
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!