amkhrjee
amkhrjee

Reputation: 946

Redirect is not working with onClick method in anchor tag

I want to use a div as my button and here is the code for that :

<a onClick={handleLogin()}>
    <div   className="blu-button">
     <p  id="button-text-blu">LOGIN AS ADMIN <span role="img" aria-label="emoji"> 🔐</span></p>
     <div  className="blu-button-wrapper"></div>
    </div>
</a>

And here is my handleLogin function :

const handleLogin = () => {
      return <Redirect to="/amnet/auth"/>
}

The browser is not throwing any error. It's just the Redirect thing that's not working. I have already tried console logging the thing and it worked.

P.S. The application is being developed in React.

Upvotes: 0

Views: 335

Answers (2)

louis.sugar
louis.sugar

Reputation: 191

I'd recommend using props.history.push instead of the redirect component.

If you absolutely must use the redirect component (for example if you're on react < 16.3) you need to conditionally render the component within the rendering function of the component the button is in

Upvotes: 1

Sarthak Aggarwal
Sarthak Aggarwal

Reputation: 2312

Try this.

Use useHistory hook if you have a functional component

import { useHistory } from "react-router-dom";
let history = useHistory();
const handleLogin = () => {
      history.push("/amnet/auth")
}

if class-based component:

const handleLogin = () => {
      this.props.history.push("/amnet/auth")
}

Upvotes: 1

Related Questions