Home > Enterprise >  OnClick not a function React JavaScript
OnClick not a function React JavaScript

Time:08-31

Can somebody please Explain why this onClick doesn't work -- it says -- Expected onClick listener to be a function, instead got a value of object type. at button at div at SignIn at section at div -- not entirely sure why this wouldnt be considered a function because how would the function be added to the call stack if not clicked?

const auth = firebase.auth();
// const fireStore = firebase.fireStore();
const App = () => {
    const [user] = useAuthState(auth);
// functions
const signInWithGoogle = () => {
    console.log("click");

    // const provider = new firebase.auth.GoogleAuthProvider();
    // auth.signInWithGoogle(provider);
};

console.log(user);
return (
    <div className="App">
        <header className="App-header">here is my app</header>
        <section>
            {user ? <ChatRoom /> : <SignIn signInWithGoogle={signInWithGoogle} />}
        </section>
    </div>
);
};
export default App;

Sign in component

import React from "react";

const SignIn = (signInWithGoogle) => {
    return (
        <div>
            <button onClick={signInWithGoogle}>Sign in with google</button>
        </div>
    );
};

export default SignIn;

CodePudding user response:

When you pass a prop, it is passed into an object. So, in order to access the function you should do signInWithGoogle.signInWithGoogle

A more elegant way could be to use object destructuring as follows:

const SignIn = ({signInWithGoogle}) => {
    return (
        <div>
            <button onClick={signInWithGoogle}>Sign in with google</button>
        </div>
    );
};

CodePudding user response:

The problem is in the SignIn component.

All React component has a props argument. Then signInWithGoogle function in i side the props object.

So the fix would be to destructure the props argument and adding brackets around “signInWithGoogle”

import React from "react";

const SignIn = ({ signInWithGoogle }) => {
    return (
        <div>
            <button onClick={signInWithGoogle}>Sign in with google</button>
        </div>
    );
};

export default SignIn;
  • Related