In React, particularly when using the react-router-dom library, NavLink is a special component type used for navigating to different routes within an application. To pass an id or other parameters via NavLink, there are several approaches you can use, as shown below:
Method One: Using Dynamic Routing
When configuring routes, you can utilize dynamic path parameters. For example, if you have a user details page and intend to pass the user's ID via a link click.
javascript// First, set up dynamic routing in your route configuration <Route path="/user/:id" component={UserDetail} /> // Then use NavLink to pass the parameter <NavLink to={"/user/${userId}"}>View User</NavLink>
Here, userId is the parameter you intend to pass, and the UserDetail component can receive this parameter via match.params.id.
Method Two: Using State
Another approach is to use the state property of NavLink to pass complex state information. This is a less commonly used but valuable feature that allows you to pass not only an id but also other more complex data structures.
javascript<NavLink to={{ pathname: '/user', search: `?id=${userId}`, // You can also choose to pass via query parameters state: { id: userId } }}> View User </NavLink>
In the target component, you can access this id through location.state.id.
Example
Suppose you have a component for displaying a user list, where each user name has a link next to it that navigates you to the user's details page. Here's a simple example of using NavLink to pass the user id:
javascriptimport React from 'react'; import { NavLink } from 'react-router-dom'; function UserList({ users }) { return ( <div> <h2>User List</h2> <ul> {users.map(user => ( <li key={user.id}> {user.name} - <NavLink to={"/user/${user.id}"}>View Details</NavLink> </li> ))} </ul> </div> ); } export default UserList;
In this example, each user's detail link is dynamically generated, with user.id used to create the route for the specific user's details page.
Through these methods, the NavLink component can be very flexible for various routing navigation scenarios while passing the required data.