React Routing Redirect onClick

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


Instead of using the props.history, a better way is using the useHistory hook like below:

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

const MyComponent = (props) => {
  const history = useHistory();

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

You can route by function by like this

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

Hope this help


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