🔒 Closed Google Authentication React JS

Status
Not open for further replies.
To redirect a user to the homepage of your React app after a successful sign-in using Google, you can use the history object from React Router.

Assuming you have installed React Router and have set up your routes in your app, you can use the history.push() method to redirect the user to the homepage.

Here's an example code snippet:

JSX:
import React, { useState } from "react";
import { useHistory } from "react-router-dom";
import { signInWithGoogle } from "./firebase/auth"; // import your Google sign-in function

function SignInPage() {
  const [loading, setLoading] = useState(false);
  const history = useHistory(); // get the history object from React Router

  const handleSignInWithGoogle = async () => {
    setLoading(true);
    try {
      await signInWithGoogle(); // call your Google sign-in function
      setLoading(false);
      history.push("/"); // redirect to the homepage
    } catch (error) {
      setLoading(false);
      console.log(error);
    }
  };

  return (
    <div>
      <button onClick={handleSignInWithGoogle} disabled={loading}>
        Sign in with Google
      </button>
    </div>
  );
}

export default SignInPage;

In this example, we first import the useHistory hook from React Router. Then, we define a handleSignInWithGoogle function that calls our Google sign-in function and, upon successful authentication, redirects the user to the homepage using history.push("/").

Note that this assumes you have set up your React Router routes correctly, with a homepage route that has a path of "/". If your homepage route has a different path, replace "/" with your homepage route path in the history.push() method.
 
Status
Not open for further replies.

About this Thread

  • 3
    Replies
  • 581
    Views
  • 3
    Participants
Last reply from:
jisoo69

Trending Topics

Online now

Members online
668
Guests online
3,097
Total visitors
3,765

Forum statistics

Threads
2,328,557
Posts
29,242,974
Members
1,157,906
Latest member
kitzmali
Back
Top