navigate react router dom code example
Example 1: Programmatically navigate using react router
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 2: navigating programatically react
import { Route } from 'react-router-dom'
const Button = () => (
<Route render={({ history}) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
)} />
)
Example 3: react-router-dom redirect on click
import { useHistory } from 'react-router-dom';
function app() {
let history = useHistory();
const redirect = () => {
history.push('/your-path')
}
return (
<div>
<button onClick={redirect}>Redirect</button>
</div>
)
}
Example 4: react window navigate
window.location.href = "/insert/your/path/here".