SendGrid React

👀

This tutorial is an extension of the SendGrid Transactional Email Guide. You must have the Cloud Functions deployed to start sending email from your frontend app.

Initial Setup

Start by installing the Firebase Web SDK, then initialize the packages in the root of the project.

file_type_js_official firebase.js
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/functions';

const config = {
 // your firebase config
}

firebase.initializeApp(config);

export const app = firebase.app();
export const auth = firebase.auth();
export const functions = firebase.functions();

Transactional Email Component

The React component uses the setState hook to monintor to the user’s auth state, while sendEmail references the callable function deployed to Firebase.

file_type_js_official App.js
import React, { useState } from 'react';
import './App.css';

import * as firebase from 'firebase/app';
import { auth, functions } from './firebase';

function App() {

  const [user, setUser] = useState(null);

  auth.onAuthStateChanged(setUser);

  return (
    <div className="App">
      <h2>SendGrid Transactional Email with React</h2>
      {user ? signOutUI(user) : signInUI() }
    </div>
  );
}

function signInUI() {
  return (
    <div>
      <button onClick={() => auth.signInWithPopup(new firebase.auth.GoogleAuthProvider())}>SignIn with Google</button>
    </div>
  )
}

function signOutUI(user) {
  return (
    <div>
      
      <p>{ JSON.stringify(user) }</p>

      <hr />

      <button onClick={() => sendEmail()}>Send Email with Callable Function</button>
      <button onClick={() => auth.signOut()}>SignOut</button>
    </div>
  )
}
function sendEmail() {
  const callable = functions.httpsCallable('genericEmail');
  return callable({ text: 'Sending email with React and SendGrid is fun!', subject: 'Email from React'}).then(console.log)
}

export default App;

Q&A Chat