Home > Article > Web Front-end > How to Pass Props to Target Components in React Router\'s Link?
Pass Props in Link React-Router
React-Router's Link component allows for passing properties to target components. However, it's crucial to ensure proper route configuration to facilitate data transfer.
The issue arises when the route path does not match the intended property retrieval. In the provided code, the
<Route name="ideas" handler={CreateIdeaView} />
To resolve the issue and pass properties through the link, specify the path in the route configuration, ensuring it aligns with the parameters in the component:
<Route name="ideas" path="/:testvalue" handler={CreateIdeaView} />
The :testvalue placeholder parameter corresponds to the property passed in the :
<Link to="ideas" params={{ testvalue: "hello" }} />
Properties can now be accessed in the target component's render method:
render: function() { console.log(this.props.match.params.testvalue); // logs "hello" }
Using hooks in functional components, you can access props like this:
const CreatedIdeaView = () => { const { testvalue } = useParams(); console.log(testvalue); // logs "hello" }
Alternatively, if you need to pass query parameters instead of path parameters, you can use it like this:
<Link to={{pathname: '/ideas', query: {testvalue: "hello"}}} />
In the target component:
componentDidMount() { console.log(this.props.location.query.testvalue) // logs "hello" }
The above is the detailed content of How to Pass Props to Target Components in React Router\'s Link?. For more information, please follow other related articles on the PHP Chinese website!