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.
xxxxxxxxxx
1
import { useHistory } from 'react-router-dom'
2
3
const App = () => {
4
const history = useHistory();
5
const clickHandler = () => {
6
history.push('/path/to/your/page');
7
};
8
return (
9
<button onClick={clickHandler} >Go to my path</button>
10
);
11
};
12
13
export default App;
xxxxxxxxxx
1
import { Redirect } from 'react-router-dom'
2
3
const App = () => {
4
const handleClick= () => {
5
<Redirect to='/path/to/your/page'>;
6
};
7
return (
8
<button onClick={handleClick} >Go to my path</button>
9
);
10
};
11
12
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.