REACT USEHISTORY code example
Example 1: usehistory example
import { useHistory } from 'react-router-dom';
function Home() {
const history = useHistory();
return <button onClick={() => history.push('/profile')}>Profile</button>;
}
Example 2: usehistory, uselocation
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
Example 3: useHistory goback
import {useHistory} from "react-router-dom";
const history = useHistory();
<button onClick={() => history.goBack()}>Go Back</button>
Example 4: usematch react router
import React from 'react'
import ReactDOM from 'react-dom'
import { useParams } from 'react-router-dom'
function BlogPost() {
let { slug } = useParams()
}
ReactDOM.render(
<Router>
<div>
<Switch>
{}
<Route path="/posts/:slug">
<BlogPost />
</Route>
</Switch>
</div>
</Router>,
document.getElementById('root')
)
Example 5: react router dom current path hook
import { useLocation } from 'react-router-dom'
const MyComponent = () => {
const location = useLocation()
return <span>Path is: {location.pathname}</span>
}
export default MyComponent
Example 6: 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')