What is useParams?
- Definition: useParams is a hook provided by React Router that lets you access parameters from the current URL.
- Use Case: It's commonly used when you need to extract values from the URL to display specific content, such as user profiles or blog posts.
Setting Up React Router
Before we can use useParams, we need to set up React Router in our application. Here’s a basic example:
Install React Router:
npm install react-router-dom
App.js:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import UserProfile from './UserProfile';
function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/user/:username" component={UserProfile} />
</Switch>
</Router>
);
}
export default App;
Using useParams in a Component
Now, let's use the useParams hook to extract the username parameter from the URL.
UserProfile.js:
import React from 'react';
import { useParams } from 'react-router-dom';
function UserProfile() {
const { username } = useParams();
return (
<div>
<h1>User Profile</h1>
<p>Username: {username}</p>
</div>
);
}
export default UserProfile;
In this example:
- Route Setup: The App.js file sets up two routes: the home page (/) and a user profile page (/user/:username).
- Parameter Extraction: In UserProfile.js, the useParams hook extracts the username parameter from the URL.
Complete Example
Here’s a more detailed example to illustrate a complete use case.
App.js:
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import UserProfile from './UserProfile';
function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/user/:username" component={UserProfile} />
</Switch>
</Router>
);
}
export default App;
Home.js:
import React from 'react';
import { Link } from 'react-router-dom';
function Home() {
return (
<div>
<h1>Home Page</h1>
<p>
Go to <Link to="/user/johndoe">John Doe's Profile</Link>
</p>
</div>
);
}
export default Home;
UserProfile.js:
import React from 'react';
import { useParams } from 'react-router-dom';
function UserProfile() {
const { username } = useParams();
return (
<div>
<h1>User Profile</h1>
<p>Username: {username}</p>
</div>
);
}
export default UserProfile;
Verdict
The useParams hook is a simple yet powerful tool for managing dynamic routes in React applications. By extracting parameters from the URL, you can create more flexible and user-friendly web applications. Whether you're building a blog, an e-commerce site, or a social network, understanding how to use useParams is essential.
Comments
(0)