import useParams code example
Example 1: usematch react router
import React from 'react'
import ReactDOM from 'react-dom'
import { useParams } from 'react-router-dom'
function BlogPost() {
// We can call useParams() here to get the params,
// or in any child element as well!
let { slug } = useParams()
// ...
}
ReactDOM.render(
<Router>
<div>
<Switch>
{/* No weird props here, just use
regular `children` elements! */}
<Route path="/posts/:slug">
<BlogPost />
</Route>
</Switch>
</div>
</Router>,
document.getElementById('root')
)
Example 2: react router dom current path hook
import { useLocation } from 'react-router-dom'
// Location is, for example: http://localhost:3000/users/new
// Care! MyComponent must be inside Router to work
const MyComponent = () => {
const location = useLocation()
// location.pathname is '/users/new'
return <span>Path is: {location.pathname}</span>
}
export default MyComponent
Example 3: useHistory react-router-dom
In react-router-dom version 6
useHistory() is replaced by useNavigate() ;
import {useNavigate} from 'react-router-dom';
const navigate = useNavigate();
navigate('/home')
Example 4: useparams
import {
BrowserRouter as Router,
Switch,
Route,
useParams
} from "react-router-dom";
function BlogPost() {
let { slug } = useParams();
return <div>Now showing post {slug}</div>;
}
ReactDOM.render(
<Router>
<Switch>
<Route exact path="/">
<HomePage />
</Route>
<Route path="/blog/:slug">
<BlogPost />
</Route>
</Switch>
</Router>,
node
);
Example 5: useparams
import { useParams } from "@reach/router"
// route: /user/:userName
const User = () => {
const params = useParams();
return <h1>{params.userName}</h1>
)