Get the ID from a URL in React and React Router

Created at 15-Dec-2022 , By samar

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.

Buy Me A Coffee

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.