In React Router v6, passing parameters to the <Link> component can be achieved in several ways. Parameters are commonly used to pass information between different pages or components, such as user IDs or product details. Here are the primary methods:
1. Using Path Parameters
Path parameters are part of the route path and are typically used to identify resources, such as user IDs or product IDs. When configuring routes, you define parameters within the path and specify their values in the to attribute of the <Link> component.
Example code:
javascriptimport { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'; function App() { return ( <Router> <div> <h2>User List</h2> <ul> <li><Link to="/user/1">User 1</Link></li> <li><Link to="/user/2">User 2</Link></li> </ul> <Routes> <Route path="/user/:id" element={<User />} /> </Routes> </div> </Router> ); } function User() { // Use the useParams hook to retrieve parameters const { id } = useParams(); return <div>User ID: {id}</div>; }
In this example, <Link to="/user/1"> navigates the user to /user/1, where 1 is passed via path parameters.
2. Using Query Parameters
Query parameters (also known as search parameters) can be set in the URL query string and directly encoded in the to attribute of <Link>.
Example code:
javascriptimport { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'; import { useSearchParams } from 'react-router-dom'; function App() { return ( <Router> <div> <h2>Product List</h2> <ul> <li><Link to="/product?name=Phone">Phone</Link></li> <li><Link to="/product?name=Computer">Computer</Link></li> </ul> <Routes> <Route path="/product" element={<Product />} /> </Routes> </div> </Router> ); } function Product() { // Use the useSearchParams hook to retrieve query parameters const [searchParams] = useSearchParams(); const name = searchParams.get('name'); return <div>Product Name: {name}</div>; }
In this example, <Link to="/product?name=Phone"> passes the product name via query parameters.
3. Using State
You can use the state property of <Link> to pass more complex data structures, such as objects.
Example code:
javascriptimport { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'; function App() { return ( <Router> <div> <h2>Information List</h2> <ul> <li><Link to="/info" state={{ message: 'Hello World' }}>View Information</Link></li> </ul> <Routes> <Route path="/info" element={<Info />} /> </Routes> </div> </Router> ); } function Info() { const location = useLocation(); const { message } = location.state || {}; return <div>Information: {message}</div>; }
In this example, the state attribute of <Link> passes an object containing a message. In the target component, this state can be accessed using the useLocation hook.
These are the common methods for passing parameters in React Router v6; select the appropriate method based on your specific requirements.