React: Firebase auth function calls by itself when the component renders

Viewed 195

GOAL: I am making a login by Google functionality in my website using Firebase Auth. I want When the user clicks the Signin link in the Navbar, he is redirected to the login page, in the login page, there is a dummy email/password input form and a Login with Google Button. When the user clicks on the Login with Google button he should be redirected to all the email list, so that he can choose from which he wants to login.

ERROR: When the user clicks on the Signin Link in the Navbar the Login Route opens up and the function for the firebase auth is called by itself, without even clicking the Google Signin Button and the user is redirected to the emails list page.

Login.jsx:

import React from 'react'
import {Link} from "react-router-dom"
import './components/css/login.css'
import googleLogo from "./components/svg/google.svg"
import brandLogo from "./components/img/logo1.png"
//The JS for Login is in another file
import { googleSignin } from './firebase/googleLogin'

function login() {
        
        return (
            <div className="background-div" >
                <nav className="login-nav" >
                    <img src={brandLogo} alt="logo"/>
                    <h2>the<strong>Dukaandar</strong></h2>
                </nav>
                <form action="" className="login-form">
                    <h3><strong>Login into your account</strong></h3>
                    <h5 className="login-email" >Email</h5>
                    <input type="text" className="login-email-input" placeholder="Enter your email" />
                    <h5 className="login-password">Password</h5>
                    <input type="password" className="login-password-input" placeholder="Enter your password" />
                        <br />
                    <button className="login-button">Login</button>
                     <Link className="login-forgot-password">forgot password?</Link>
                         <hr />
                    // The onClick attribute in React, I expect anything to happen only after clicking this button
                    <button className="google-login" onClick={googleSignin()} > <span className="google-image"><img src={googleLogo} alt=""/></span>Login with Google</button>
                    <Link to={"/"}>Back to Home</Link>
                </form>
            </div>
            )
        
}

export default login

JS File:

import firebase from 'firebase'
   
const firebaseConfig = {
   // Key value pairs of my config
};

      // Initialize Firebase
      firebase.initializeApp(firebaseConfig);

      //This is the Function which has to be called on button click
      function googleSignin() {
        var provider = new firebase.auth.GoogleAuthProvider();
        firebase
        .auth()
        .signInWithRedirect(provider)
        .then(function(result) {
       // This gives you a Google Access Token. You can use it to access the Google API.
       var token = result.credential.accessToken;
       // The signed-in user info.
       var user = result.user;
       console.log(user);
       console.log(result);

       })
      .catch(function(error) {
       console.log(error);
      
      });

    }

    export { googleSignin }

While searching for it I came to know about lifecycle methods which occurs when the component is rendered, if that is the case here, how to stop them to call itself?

As told in answer below and from my finding onClick{ () => googleSignin } also does not work, and also when I call the function with parenthesis googleSignin(), the function is atleast called but withot it nothing hapens. I suspect there can be a React Router problem also, but I don't know.

Thank you in advance

Full Source Code of the Website on Github, Live Preview on Netlify

2 Answers

By adding parenthesis on the onClick handler, you are invoking the function as soon as it is loaded. Remove the parenthesis and it will work.

<button className="google-login" onClick={googleSignin}>
  <span className="google-image">
    <img src={googleLogo} alt="" />
  </span>
  Login with Google
</button>

When the Browser sees the function is being called and not referenced on the OnClick method, it takes the responsibility and calls the function by itself. So, we have to free the Browser from its responsibility, and let the Function to be called only when the User clicks on the button.

Make a Handler function to free the Browser from its responsibility:

function handleClick(e) {
        e.preventDefault();
        googleSignin();
        console.log('The link was clicked.');
 }

Reference handleClick in your onClick method:

<button className="google-login" 
  //Reference handleClick here.
  onClick={handleClick}>
    <span className="google-image">
      <img src={googleLogo} alt=""/>
    </span>
  Login with Google
</button>

This will solve the problem.

Related