Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 15, 2022 02:45 am GMT

Authentication Using Firebase in React App.

In this article we will know how to authenticate users, in your web app. For this article I'm using google authentication.
Follow....

Create a Firebase Project

It's simple, just login with your google account in firebase, create a new project.
Image description

In that project go to Authentication's tab.
Image description

Click on Sign-in method
Image description
Go to Add New Provider, select Google.
Image description

Now, you need to create a web app in your project
Image description
Image description
Image description
Copy the configuration file.
Now, open your fav IDE and create a React Project.
In src folder create a file name fb.config.js / .ts
Image description
also, don't forget to install firebase.

npm i firebase

we're using context to use state of user authentication in our app. create a authContext.tsx file.

import { createContext, ReactComponentElement, ReactElement, useContext, useEffect, useState } from 'react'import { User, GoogleAuthProvider, signInWithPopup, signOut, onAuthStateChanged } from "firebase/auth"import { auth, app } from "./fb.config"interface value {    user: User | null,    logInUser: () => void,    logOutUser: () => void,}const AuthCont = createContext<User | null>(null)export const useAuthContext = () => {    return useContext(AuthCont)}export default function authContext({ children }: { children: ReactElement }) {    const [user, setUser] = useState<null | User>(null)    useEffect(() => {        onAuthStateChanged(auth, (user) => {            setUser(user)        })    }, [])    const logInUser = () => {        const provider = new GoogleAuthProvider()        signInWithPopup(auth, provider)            .then((res) => {                setUser(res.user)            })            .catch((err) => {                console.log(err)            })    }    const logOutUser = () => {        signOut(auth)        setUser(null)    }    const value = {        user,        logInUser,        logOutUser    }    return (        <AuthCont.Provider value={user}>            {children}        </AuthCont.Provider>    )}

Now we just need to put this on top of our app.tsx, then we can use it in any child component.
Go to main.tsx file and put this code.

import React from 'react'import ReactDOM from 'react-dom/client'import App from './App'import './index.css'import AuthProvider from "./authContext"ReactDOM.createRoot(document.getElementById('root')!).render(  <React.StrictMode>    <AuthProvider>      <App />    </AuthProvider>  </React.StrictMode>)

Original Link: https://dev.to/itskunal/authentication-using-firebase-in-react-app-3jc6

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To