How to Update Link Component in React

This article explains how to update and manipulate the Link component in React Router. You will learn how to dynamically change its destination path using state, pass and update route state, style active links, and adapt your code to the latest React Router standards.

1. Dynamically Updating the Destination (to Prop)

The most common way to update a Link component is by changing its target destination. Since the to prop accepts variables, you can use React state to dynamically update where the link points.

import React, { useState } from 'react';
import { Link } from 'react-router-dom';

function ProductPage() {
  const [productId, setProductId] = useState('123');

  return (
    <div>
      <button onClick={() => setProductId('456')}>
        Switch to Product 456
      </button>
      
      {/* The Link destination updates automatically when productId changes */}
      <Link to={`/products/${productId}`}>
        View Product
      </Link>
    </div>
  );
}

You can update the data passed to the target route by using the state prop. This allows you to send background data to the next page without displaying it in the URL.

import { Link } from 'react-router-dom';

function UserProfile() {
  const userData = { name: 'Alice', role: 'Admin' };

  return (
    <Link 
      to="/dashboard" 
      state={{ user: userData }}
    >
      Go to Dashboard
    </Link>
  );
}

To retrieve and use this updated state on the destination page, use the useLocation hook:

import { useLocation } from 'react-router-dom';

function Dashboard() {
  const location = useLocation();
  const { user } = location.state || {};

  return <h1>Welcome, {user?.name}</h1>;
}

If you need to update the visual style of a link when it is active (e.g., in a navigation menu), use the NavLink component instead of Link. It automatically detects the active route and applies classes or styles.

import { NavLink } from 'react-router-dom';

function Navigation() {
  return (
    <nav>
      <NavLink 
        to="/home" 
        style={({ isActive }) => ({
          color: isActive ? 'blue' : 'black',
          fontWeight: isActive ? 'bold' : 'normal'
        })}
      >
        Home
      </NavLink>
    </nav>
  );
}

4. Upgrading to React Router v6 Standards

If you are updating older React Router code (v5 or earlier) to React Router v6, keep these changes in mind for the Link component:

Example of upgraded relative path:

// React Router v5 (Old)
<Link to={`${match.url}/details`}>Details</Link>

// React Router v6 (Updated)
<Link to="details">Details</Link>