Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Routing Redirect onClick

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>
        );
    }
like image 600
Yashank Avatar asked Jul 18 '18 03:07

Yashank


1 Answers

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');
like image 179
Mohammad Reza Avatar answered Sep 20 '22 14:09

Mohammad Reza