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