Authentication Using Firebase in React App. 🤺🔥

On this article we’ll know how you can authenticate customers, in your internet app. For this text I am utilizing google authentication.
Comply with….



Create a Firebase Mission

It is easy, simply login together with your google account in firebase, create a brand new challenge.

In that challenge go to Authentication’s tab.
Image description

Click on on Signal-in technique
Image description
Go to Add New Supplier, choose Google.
Image description

Now, you want to create an internet app in your challenge
Image description
Image description
Image description
Copy the configuration file.
Now, open your fav IDE and create a React Mission.
In src folder create a file title fb.config.js / .ts
Image description
additionally, remember to put in firebase.

npm i firebase
Enter fullscreen mode

Exit fullscreen mode

we’re utilizing context to make use of state of person authentication in our app. create a authContext.tsx file.

import { createContext, ReactComponentElement, ReactElement, useContext, useEffect, useState } from 'react'
import { Consumer, GoogleAuthProvider, signInWithPopup, signOut, onAuthStateChanged } from "firebase/auth"
import { auth, app } from "./fb.config"

interface worth  null,
    logInUser: () => void,
    logOutUser: () => void,


const AuthCont = createContext<Consumer | null>(null)

export const useAuthContext = () => {
    return useContext(AuthCont)
}

export default operate authContext({ youngsters }: { youngsters: ReactElement }) {
    const [user, setUser] = useState<null | Consumer>(null)
    useEffect(() => {
        onAuthStateChanged(auth, (person) => {
            setUser(person)
        })
    }, [])

    const logInUser = () => {
        const supplier = new GoogleAuthProvider()
        signInWithPopup(auth, supplier)
            .then((res) => {
                setUser(res.person)
            })
            .catch((err) => {
                console.log(err)
            })
    }
    const logOutUser = () => {
        signOut(auth)
        setUser(null)
    }

    const worth = {
        person,
        logInUser,
        logOutUser
    }
    return (
        <AuthCont.Supplier worth={person}>
            {youngsters}
        </AuthCont.Supplier>
    )
}
Enter fullscreen mode

Exit fullscreen mode

Now we simply have to put this on high of our app.tsx, then we are able to use it in any baby part.
Go to predominant.tsx file and put this code.

import React from 'react'
import ReactDOM from 'react-dom/consumer'
import App from './App'
import './index.css'
import AuthProvider from "./authContext"

ReactDOM.createRoot(doc.getElementById('root')!).render(
  <React.StrictMode>
    <AuthProvider>
      <App />
    </AuthProvider>
  </React.StrictMode>
)
Enter fullscreen mode

Exit fullscreen mode

Add a Comment

Your email address will not be published. Required fields are marked *