Get the ID from a URL in React and React Router
To get the ID from a URL in React, you can use the useParams() hook in react. It contains an object of key-value pairs ({userId: '1'}
) and you can get that value by passing the parameter (userId) which is a placeholder you declare in the route using path="/users/:userId"
.
For example, if your route path is defined as <Route path="/users/:userId" element={<Users />} />
, you can access the value of userId parameter from URL in the component like const params = useParams();
{params.userId}
.
import React from 'react';
import {BrowserRouter as Router, Route, Link, Routes, useParams} from 'react-router-dom';
function Home() {
return ( <h2> Welcome to react </h2> );
}
function Users() {
const params = useParams();
return ( <h2>userId is {params.userId}</h2> );
}
export function App(props) {
return (
<div className='App'>
<Router>
<Link to="/users/1">User</Link>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/users/:userId" element={<Users />} />
</Routes>
</Router>
</div>
);
}
You can simply use the above code snippet for example code or you can create different components for home and user and include it in your app.js using import method.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
Don't forget to share this article! Help us spread the word by clicking the share button below.
We appreciate your support and are committed to providing you valuable and informative content.
We are thankful for your never ending support.
Random Code Snippet Queries: React
- Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead
- We're unable to detect target browsers. react app
- Uncaught Error: useHref() may be used only in the context of a <Router> component
- How to pass dynamic URL to Link in react ?
- Module not found: Error: Can't resolve 'prop-types'
- Module Not Found: Can’T Resolve ‘Jquery’ In React
- React-dom.development.js:86 Warning: validateDOMNesting(...):
- How do I link to an external URL in React?