How to direct to keycloak to authenticate on click on a button in react?

I added the following code to the click event handler of the login button-

onClick={() => {

          alert("User logged in");
          const keycloak = Keycloak({
            realm: "Showcase",
            url: "https://*****/auth/",
            clientId: "****",
          });
          keycloak
            .init({ onLoad: "login-required" })
            .then((authenticated) => {
              if (authenticated) {
                alert("Authernicated");
                alert(JSON.stringify(keycloak));


                // setTimeout(5000)
                keycloak.loadUserInfo().then((userInfo) => {
                  alert(JSON.stringify(userInfo));
                });
                setTimeout(function () {
                  alert("time out");
                  alert(JSON.stringify(keycloak));
                  alert(authenticated);
                  //this.setState({ keycloak: keycloak, authenticated: authenticated })
                  // setTimeout(5000)
                  keycloak.loadUserInfo().then((userInfo) => {
                    alert(JSON.stringify(userInfo));
                  });
                }, 500);
              } else {
                alert("not");
              }
            });
            
        }}

The logic within then doesn’t get executed on clicking for the first time .

After clicking the second time only I see the alerts.

Can someone help me fix this issue?

I can’t see your specific mistake but alternatively you could try to initialize keycloak on page load with “check-sso” instead of “login-required”
keycloak.init({ onLoad: "check-sso" })

and login onClick via
keycloak.login()
or
keycloak.getLoginUrl()
and so forth.

@snet To integrate keycloak into your react app you wouldn’t put this logic into a button click. If you want an easy way to setup you could use: react-keycloak/README.md at master · react-keycloak/react-keycloak · GitHub