EN
React / react-router - navigate to a route from event handler
0
points
In this short article, we would like to show you how to enter a direct path (e.g. from event handler) without using Link in React.
1. Using useHistory
import { useHistory } from 'react-router-dom'
const App = () => {
const history = useHistory();
const clickHandler = () => {
history.push('/path/to/your/page');
};
return (
<button onClick={clickHandler} >Go to my path</button>
);
};
export default App;
2. Using <Redirect>
import { Redirect } from 'react-router-dom'
const App = () => {
const handleClick= () => {
<Redirect to='/path/to/your/page'>;
};
return (
<button onClick={handleClick} >Go to my path</button>
);
};
export default App;
Note:
In
<Redirect>
the new location will replace the current location in the history stack, buthistory.push()
will push the new entry on it.