I am learning useParams
hook in react. I have a URL like this and need to be able to extract the letter 9 from it.
http://localhost:3010/9/solution
How can I go about this ?
Answers
To extract the parameter from a URL in a React component using the useParams
hook, follow these steps:
-
Ensure you have
react-router-dom
installed in your project. If not, you can install it using npm or yarn:npm install react-router-dom
or
yarn add react-router-dom
-
Set up your routes in your
App.js
or a similar file where you define your routes:import React from 'react'; import { BrowserRouter as Router, Route, Routes, } from 'react-router-dom'; import Solution from './Solution'; function App() { return ( <Router> <Routes> <Route path="/:id/solution" element={<Solution />} /> </Routes> </Router> ); } export default App;
-
Create the
Solution
component where you want to extract the parameter from the URL:import React from 'react'; import { useParams } from 'react-router-dom'; function Solution() { const { id } = useParams(); return ( <div> <h1>Solution Component</h1> <p>The extracted ID is: {id}</p> </div> ); } export default Solution;
Here's a breakdown of what's happening:
- In the
App
component, we set up a route with the path/:id/solution
. The:id
part is a URL parameter that we want to extract. - The
Solution
component uses theuseParams
hook fromreact-router-dom
to access the URL parameters. TheuseParams
hook returns an object where the keys are the names of the URL parameters, and the values are the corresponding values from the URL. - In the
Solution
component, we destructureid
from the object returned byuseParams
and display it in the component.
Now, when you navigate to http://localhost:3010/9/solution
, the Solution
component will extract the id
parameter (which is 9
in this case) and display it.