Home >Web Front-end >JS Tutorial >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
Solution:
Add the path parameter to the
<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!