Using the useParams Hook in React
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. How Can I Go About This? 3 2 Answers I'm...
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.
How can I go about this ?
I'm assuming you're using react router, if you define a route like this for example:
<Route path="/:id/about">
<About />
</Route>
Notice that you define the path with this :id notation, that means that the id will be the param in this specific case. Then you create a Link component
<Link to="/2/about">About</Link>
And in your component that in this example is the about component you can use the hook like this:
function About() {
const { id } = useParams();
return (
<div>
<h2>Now showing post {id}</h2>
</div>
);
}
I have this code sandbox if you want to check the result
Assuming you are using react-router, then you should use Browser Router in your React app:
and then declare a route like:
<Route path="/{id}/solution" component={Component} />
and then in your Component you'll be able to use it:
const { id } = useParams();