Keywords: React Router | Parameter Passing | Link Component | Route Parameters | State Management
Abstract: This comprehensive guide explores various methods for passing parameters through React Router's Link component, covering the evolution from early versions to the latest (v6). It provides detailed analysis of three main approaches: route parameters, query parameters, and state passing, with complete code examples demonstrating how to receive and utilize these parameters in both class and functional components. The article also compares API changes across different React Router versions, offering developers complete parameter passing solutions.
Overview of React Router Parameter Passing Mechanisms
In React application development, data transfer between routes is a common requirement. React Router provides multiple approaches to achieve this goal, primarily including route parameters, query parameters, and state passing mechanisms. Understanding the differences and appropriate use cases for these mechanisms is crucial for building efficient single-page applications.
Route Parameter Passing
Route parameters represent the most direct method of parameter passing, carrying data through the URL path itself. In earlier versions of React Router, developers needed to use the params property to pass parameters:
// React Router v1/v2 approach
<Link to="ideas" params={{ testvalue: "hello" }}>Create Idea</Link>
The corresponding route configuration requires parameter placeholders:
// Route configuration
<Route name="ideas" path="/:testvalue" handler={CreateIdeaView} />
In the target component, these parameters can be accessed via this.props.params:
// Accessing parameters in class components
class CreateIdeaView extends React.Component {
render() {
const { testvalue } = this.props.params;
console.log('Received parameter:', testvalue);
return (
<div>
<h1>Create Post: {testvalue}</h1>
</div>
);
}
}
Modern React Router Parameter Passing
Starting from React Router v4, the API underwent significant changes. Modern versions recommend using object-form to properties:
// React Router v4+ recommended approach
const backUrl = '/some/other/value';
// Using pathname and search
<Link to={{
pathname: `/ideas/${this.props.testvalue}`,
search: `?backUrl=${backUrl}`
}}>
Create Idea
</Link>
// Or using string form
<Link to={`/ideas/${this.props.testvalue}?backUrl=${backUrl}`}>
Create Idea
</Link>
Parameter Reception in Functional Components
In functional components, React Router provides specialized Hooks for accessing route parameters:
import { useParams, useLocation } from 'react-router-dom';
const CreateIdeaView = () => {
const { testvalue } = useParams();
const location = useLocation();
// Parse query parameters
const searchParams = new URLSearchParams(location.search);
const backUrl = searchParams.get('backUrl');
console.log('Route parameter:', testvalue);
console.log('Query parameter:', backUrl);
return (
<div>
<h1>Create Post: {testvalue}</h1>
{backUrl && <p>Back URL: {backUrl}</p>}
</div>
);
};
State Parameter Passing
Beyond URL parameters, React Router also supports data passing through state, which doesn't expose data in the URL:
// Passing state data
<Link
to="/onboarding/profile"
state={{
from: "occupation",
userData: { name: "John", experience: 5 }
}}
>
Next Step
</Link>
Receiving state data in the target component:
import { useLocation } from 'react-router-dom';
function Profile() {
const location = useLocation();
const { from, userData } = location.state || {};
return (
<div>
<p>From: {from}</p>
{userData && (
<p>Username: {userData.name}, Experience: {userData.experience} years</p>
)}
</div>
);
}
Version Migration Considerations
React Router has significant API changes between different versions. In the migration from v1 to v2, the query and state properties were deprecated in favor of location descriptors:
// v1.0.x (deprecated)
<Link to="/foo" query={{ the: 'query' }}/>
// v2.0.0+ (recommended)
<Link to={{ pathname: '/foo', query: { the: 'query' } }}/>
Practical Application Example
Below is a complete example demonstrating the use of multiple parameter passing methods in complex scenarios:
import React from 'react';
import { BrowserRouter, Switch, Route, Link, useParams, useLocation } from 'react-router-dom';
const Ideas = ({ location }) => {
const { id } = useParams();
const { item } = location.state || {};
return (
<div>
<h3>Ideas Page</h3>
<p>ID: {id}</p>
{item && <p>Item: {JSON.stringify(item)}</p>}
<Link
to={{
pathname: `/hello/world1`,
search: '?thing=asdf&another1=stuff',
state: { fromIdeas: true }
}}
>
Go to World 1
</Link>
</div>
);
};
const World = () => {
const { WORLD } = useParams();
const location = useLocation();
const searchParams = new URLSearchParams(location.search);
return (
<div>
<h2>Welcome to {WORLD}</h2>
<p>Query Param 1: {searchParams.get('thing')}</p>
<p>Query Param 2: {searchParams.get('another1')}</p>
{location.state?.fromIdeas && (
<p>This page was navigated from the Ideas page</p>
)}
</div>
);
};
const App = () => {
return (
<BrowserRouter>
<nav>
<Link
to={{
pathname: '/ideas/222',
state: {
item: { okay: 123 },
id: 222
}
}}
>
Ideas
</Link>
</nav>
<Switch>
<Route path="/ideas/:id" component={Ideas} />
<Route path="/hello/:WORLD?" component={World} />
</Switch>
</BrowserRouter>
);
};
export default App;
Best Practice Recommendations
When choosing parameter passing methods, consider the following factors: use route parameters for identifying data, query parameters for optional filtering conditions, and state passing for sensitive or temporary data. Making appropriate choices in parameter passing methods can enhance application maintainability and user experience.
Conclusion
React Router provides flexible parameter passing mechanisms, evolving from early params properties to modern location descriptors and Hooks, with APIs continuously adapting to development needs. Understanding the differences and appropriate use cases for these mechanisms, combined with selecting suitable parameter passing methods based on specific business requirements, is key to building high-quality React applications.