'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>
        );
    }


Solution 1:[1]

You can route by function by like this

  handleOnSubmit = () => {
  this.props.history.push(`/dashboard`);
  };

Hope this help

Solution 2:[2]

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');

Solution 3:[3]

Simple, use NavLink instead of button

import { NavLink } from 'react-router-dom'

<NavLink to="/dashboard"> Dashboard </NavLink>

https://reacttraining.com/react-router/web/api/NavLink

Solution 4:[4]

<Switch> component render only the first route that matches. You just need to swap your <Route> components in <Switch> case and use @Adnan shah answer to make redirect function.

P.S react router auth example

Solution 5:[5]

This happened to me once I had missed importing the component to the route.js file.

You need to reference/import files from the component to the routefile.

Solution 6:[6]

Use an a tag

<a href="/" />

Solution 7:[7]

Maybe this might help

import { useHistory } from "react-router-dom";
const history = useHistory();
<Button
onClick={this.login}
>
</Button>

login = () =>{
     history.push("/about");
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Madhan S
Solution 3 Abdullah
Solution 4 ?????? ?????????
Solution 5 Bhargav Rao
Solution 6 Chetan Jain
Solution 7 Sandeep Rana