vincent15000's avatar

Button automatically clicked on loading withtout clicking on it

Hello,

I start learning React and I have this problem.

When I load the Login page, the button is clicked automatically.

export default function Login() {
    const connectWith = (provider) => {
        socialiteService.redirect(provider);
    }

    return (
        <ViniFullscreen>
            <img className="absolute top-0 left-0 w-full h-full mask-b-from-50% mask-b-to-100%" src={home} alt="Home image" />

            <div className="h-full flex flex-col justify-center z-1 px-8 py-8">
                <ViniCard className="opacity-90 space-y-4">

                    <ViniButton type="button" fill="light" onClick={connectWith('google')}>Se connecter avec Google</ViniButton>

                    <div class="text-center">
                        <ViniLink to={routes.home}>Retour à la page d'accueil</ViniLink>
                    </div>
                </ViniCard>
            </div>
        </ViniFullscreen>
    );
}

And the button component.

export default function ViniButton(props) {
    return (
        <button
            className={clsx(
                'appearance-none w-full outline-none rounded-full px-4 py-3 cursor-pointer',
                {
                    'bg-gradient-to-r from-emerald-500 to-emerald-300 text-gray-50': props.fill === 'color',
                    'bg-gray-50 border border-emerald-300 text-gray-950': props.fill === 'light',
                    'bg-gray-950 border border-emerald-300 text-gray-50': props.fill === 'dark',
                }
            )}
            {...props}
        >
            {props.children}
        </button>
    );
}

What am I doing wrong ?

Can you help me please ?

Thanks ;).

V

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The issue is with how you are passing the onClick prop to your ViniButton component:

<ViniButton type="button" fill="light" onClick={connectWith('google')}>
    Se connecter avec Google
</ViniButton>

Here, connectWith('google') is calling the function immediately when the component renders, instead of passing a function to be called when the button is clicked. This is why the button is "clicked" automatically on page load.

Solution:
Wrap the function call in an anonymous function so it is only called when the button is actually clicked:

<ViniButton
    type="button"
    fill="light"
    onClick={() => connectWith('google')}
>
    Se connecter avec Google
</ViniButton>

This way, connectWith('google') will only be executed when the button is clicked.

Summary:

  • onClick={connectWith('google')} → calls the function immediately (wrong)
  • onClick={() => connectWith('google')} → passes a function to be called on click (correct)

Let me know if you need more explanation!

1 like

Please or to participate in this conversation.