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

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

Barbara Streisand
Release: 2024-11-01 06:10:02
Original
185 people have browsed it

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

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

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

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

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!

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!