Home >Web Front-end >JS Tutorial >How to Pass Props in React-Router\'s \'Link\' Component?
Pass Props in React-Router's "Link"
When using React with React-Router, you can pass properties to a new view using a modified syntax in the component.
Updated Syntax in React-Router v4 and v5
To pass props in React-Router v4 and v5, use the following syntax:
<Link to={{ pathname: path, query: queryObject, search: searchString }}> ... </Link>
where:
Accessing Props in the Destination Component
In the destination component, you can access the props passed via the Link by using the following techniques:
Out-dated usage of withRouter higher order component:
const NewView = withRouter(OriginalView);
Current implementation using hooks:
const NewView = () => { const { testvalue } = useParams(); const { query, search } = useLocation(); return ( <div> {testvalue} {query.backUrl} </div> ); };
Example
Consider the following example:
App.js:
<Link to={{ pathname: '/ideas/:testvalue', query: { testvalue: 'hello' } }}>Create Idea</Link>
CreateIdeaView.js:
const CreateIdeaView = () => { const { testvalue } = useParams(); console.log(testvalue); // prints 'hello' return ( <div>{testvalue}</div> ); };
In this example, clicking the "Create Idea" link passes the property testvalue with the value hello to the CreateIdeaView component.
Note:
The above is the detailed content of How to Pass Props in React-Router\'s \'Link\' Component?. For more information, please follow other related articles on the PHP Chinese website!