Home >Web Front-end >JS Tutorial >How to Pass Props to a New View in React Router?

How to Pass Props to a New View in React Router?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 06:10:02274browse

How to Pass Props to a New View in React Router?

Passing Props in Link React-Router

Issue:

In a React-Router application, a Link component is not passing properties to a new view, despite the properties being included in the Link's parameters.

Solution:

Outdated Code (v1):

<Link to="ideas" params={{ testvalue: "hello" }}></Link>

<Route name="ideas" handler={CreateIdeaView} />

Up-to-date Code (v4/v5):

// Using query
<Link to={{ pathname: `/${this.props.testvalue}`, query: { backUrl } }} />

// Using search
<Link to={{ pathname: `/${this.props.testvalue}`, search: `?backUrl=${backUrl}` }} />

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

Usage:

  • The to property of the takes an object with the following properties:

    • pathname: The path of the new view.
    • params: An object containing the properties to be passed to the new view.
  • The Route component must have a path property that matches the value of the dynamic parameter in the to property.

Functional Component Example:

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

Note: The above code uses hooks from react-router-dom.

Updated Code Example:

<code class="js">const App = () => {
  return (
    <React.Fragment>
      <Link to={{ pathname: '/ideas/:itemID', itemID: 222, item: { okay: 123 } }}>Ideas</Link>
      <Switch>
        <Route exact path="/ideas/:itemID/" component={Ideas} />
        <Route path="/hello/:WORLD?/:thing?" component={World} />
      </Switch>
    </React.Fragment>
  );
};</code>

The above is the detailed content of How to Pass Props to a New View in 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