Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
113 lines (83 sloc) 2.56 KB
title lastmod publishdate author draft description type tags vimeo github
SendGrid React
2019-07-05 10:43:06 -0700
2019-07-05 10:43:06 -0700
Jeff Delaney
false
Send transactional email with SendGrid from ReactJS
lessons
react
sendgrid
346869300

{{% box emoji="👀" %}} 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. {{% /box %}}

Initial Setup

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

{{< file "js" "firebase.js" >}} {{< highlight javascript >}} 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(); {{< /highlight >}}

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 "js" "App.js" >}} {{< highlight jsx >}} 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 (

SendGrid Transactional Email with React

{user ? signOutUI(user) : signInUI() }
); }

function signInUI() { return (

<button onClick={() => auth.signInWithPopup(new firebase.auth.GoogleAuthProvider())}>SignIn with Google
) }

function signOutUI(user) { return (

  <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;

{{< /highlight >}}

You can’t perform that action at this time.