Home  >  Article  >  Web Front-end  >  How to Pass Props in Link with React-Router?

How to Pass Props in Link with React-Router?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 13:20:29817browse

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

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

Link (Search):

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

Accessing Data (Functional Component):

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

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

Example:

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

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!

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