Ive been trying to do a simple redirect to another component on button click, but for some reason it doesnt work.I want to redirect to '/dashboard' and display AdminServices from login as follows:
//index.js
ReactDOM.render(<BrowserRouter><App /></BrowserRouter>,
document.getElementById("root"));
//App.js
<Switch>
<Route path="/" component={Login} />
<Route path="/dashboard" component={AdminServices} />
</Switch>
//Login.js
<Button
onClick={this.login}
>
</Button>
login = () =>{
<Redirect to="/dashboard" />
}
//AdminServices.js
render(){
return(
<div>Test</div>
);
}
In react-router-dom v6 you can use useNavigate()
, as answered here.
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/dashboard');
if you're still using previous versions, you can use useHistory
, as Tellisense mentioned.
import { useHistory } from 'react-router-dom';
const navigate = useHistory();
navigate.push('/dashboard');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With