User Authentication In React using TypeScript and React

image

User authentication is not a luxury but required in most cases and can be a quite complex topic. Today is was my first time building a user auth in React using typescript and want to make this as easy as possible. As a beginner for the beginners

Here is the original video from where I learned how to do this

Setup

Install React with the typescript template

npx create-react-app my-app --template typescript

Install Firebase

yarn add firebase

Your folder structure should look like this

Create your firebase app

I would suggest watching this video first. You will need you firebase credentials later. Here is a link from the documentation that explains it a little deeper.

my-app ├── README.md ├── node_modules ├── package.json ├── .gitignore ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt └── src ├── App.css ├── App.tsx ├── App.test.ysx ├── index.css ├── index.ts ├── logo.svg ├── serviceWorker.ts └── setupTests.ts

Now add a /components folder under /src . Inside of the components folder, create a file called Form.tsx which will be responsible for registering our users. Inside of that file, past the following code below.

import React from 'react';
interface FormProps  {
    email:string, 
    password:string,
    emailOnChange:(event:object) => void
    passwordOnChange:(event:object) => void,
    onSubmit:(e:any) => void
}

export const Form = (props:FormProps) => {
    return (
        <>
            <form onSubmit={props.onSubmit} style={{ padding:'1rem', display:'flex', alignItems: 'start', gap:10, flexDirection:'column' }}>
                <p>Register User</p>
                <input onChange={props.emailOnChange} value={props.email} style={{padding:'0.5rem'}} type="email" placeholder="Email" required/>
                <input onChange={props.passwordOnChange} value={props.password} style={{padding:'0.5rem'}} type="password" placeholder="Password" required/>
                <button style={{ padding:'0.5rem', width:'auto'}}>Submit Form</button>
            </form>
        </>
    )
}

Next, back inside of the /src folder, add a firebase-config.ts file and paste the following code

import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth'

const firebaseConfig = {
	  //... paste in your firebase credentials
		// https://firebase.google.com/docs/web/setup
  };
  
const app = initializeApp(firebaseConfig);

export const auth = getAuth(app)

Create another folder called /functions, this will separate functions from our code to make it cleaner. Add a file named auth.ts and paste the following code

import {getAuth, createUserWithEmailAndPassword} from 'firebase/auth'
import { auth } from '../firebase-config'

export const register = async (email:string, password:string) => {
    console.log('regestering the user')
    try {
        const user = await createUserWithEmailAndPassword(auth, email, password)
        console.log(user)
    } catch(err) { console.log(err)}
}

export const login = async () => {
    
}

export const logout = async () => {
    
}

Our register function takes in a email and string from our form and passes it in as an argument to the createUserWithEmailAndPassword function from firebase/auth.

Now inside of App.tsx paste the following code

import React, {useState} from 'react';
import './App.css';
import { Form } from './components/Form'
import { register, login, logout } from './functions/auth'


function App() {
  const [emailValue, setEmailValue] = useState<string>("TRet")
  const [passwordValue, setPasswordValue] = useState<string>("twet")
  const emailOnChange = (e:any) => setEmailValue(e.target.value)
  const passwordOnChange = (e:any) => setPasswordValue(e.target.value)

  const handleOnSubmit = (e:any) => {
    e.preventDefault()
    register(emailValue, passwordValue)
  }
  return (
    <div className="App">
      <Form onSubmit={handleOnSubmit} emailOnChange={emailOnChange}  passwordOnChange={passwordOnChange}  email={emailValue} password={passwordValue} />
    </div>
  );
}

export default App;

Now we have everything in the same place . Our handleOnSubmit function contains a e.preventDefault() that will prevent the page from refreshing before our register() finishes executing.

When before submitting the form, open up your console in your browser to see the response. You should see this in the browser console once you enter in your form details

UserCredentialImpl {user: UserImpl, providerId: null, _tokenResponse: {…}, operationType: 'signIn'}

And thats it. A honestly straight to the point article on using Typescript and React!

Want to start a project with me or have any requests for the next articles I should write? Hit me up at christopher.clemmons2020@gmail.com