Home >Web Front-end >JS Tutorial >How to Pass Props in React-Router\'s \'Link\' Component?

How to Pass Props in React-Router\'s \'Link\' Component?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 04:44:02723browse

How to Pass Props in React-Router's

Pass Props in React-Router's "Link"

When using React with React-Router, you can pass properties to a new view using a modified syntax in the component.

Updated Syntax in React-Router v4 and v5

To pass props in React-Router v4 and v5, use the following syntax:

<Link to={{ pathname: path, query: queryObject, search: searchString }}>
  ...
</Link>

where:

  • pathname is the path to the new view.
  • query is an object containing query parameters.
  • search is a string representing the query string, such as ?foo=bar.

Accessing Props in the Destination Component

In the destination component, you can access the props passed via the Link by using the following techniques:

Out-dated usage of withRouter higher order component:

  • Wrap the destination component with withRouter, which provides access to the match and location props:
const NewView = withRouter(OriginalView);

Current implementation using hooks:

  • Use the useParams and useLocation hooks within the functional component to access the match and location props:
const NewView = () => {
  const { testvalue } = useParams();
  const { query, search } = useLocation();

  return (
    <div>
      {testvalue} {query.backUrl}
    </div>
  );
};

Example

Consider the following example:

App.js:

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

CreateIdeaView.js:

const CreateIdeaView = () => {
  const { testvalue } = useParams();
  console.log(testvalue); // prints 'hello'

  return (
    <div>{testvalue}</div>
  );
};

In this example, clicking the "Create Idea" link passes the property testvalue with the value hello to the CreateIdeaView component.

Note:

  • The path in the Link component should include the parameter placeholder, e.g. path: '/ideas/:testvalue'.
  • The useParams hook returns an object with all the parameters defined in the path.
  • The useLocation hook returns an object with information about the current location, including query and search.
  • The query is an object containing key-value pairs, while the search string contains the entire query string.

The above is the detailed content of How to Pass Props in React-Router\'s \'Link\' Component?. 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