To redirect a user to a specific page, the useHistory
Hook from react-router-dom
is convenient.
javascriptimport React from 'react'; import { useHistory } from 'react-router-dom'; const App = () => { const history = useHistory(); const redirectMe = (url) => { // Redirects the user to url history.push(url); } return( <button onClick = {() => redirectMe('/')}>Click me to redirect</button> ); } export default App;
You can also redirect the user without using the useHistory
Hook. Using window.location.href
will do the job as well.
javascriptimport React from 'react'; const App = () => { const redirectMe = (url) => { // Redirects the user to url window.location.href = url; } return( <button onClick = {() => redirectMe('/')}>Click me to redirect</button> ); } export default App;
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.