DEV Community

loading...
Cover image for Add Formspree Formbutton to a Gatsby site

Add Formspree Formbutton to a Gatsby site

DeviousLab
I'm aiming to become proficient in the MERN stack and eventually become a full-stack developer. Attempting to gain knowledge in the cloud computing area with AWS and in DevOps.
・1 min read

I was looking to add the Formexpress button to a Gatsby site I was developing as a method of contacting the business. In normal HTML you could have probably pasted the script tag easily but in Gatsby it's not so simple.

My method was to create the gatsby-ssr.js file in the root of my working directory and post the code there so that the script tag appears on the body.

This is what I wrote in the file:

import React from 'react';
export const onRenderBody = ({ setPostBodyComponents }, pluginOptions) => {
    setPostBodyComponents([
        <script key="formspreeBase" src="https://formspree.io/js/formbutton-v1.min.js" type="text/javascript" aysnc />,
        <script
            key="formspreeWindow"
            dangerouslySetInnerHTML={{
                __html: `
                window.formbutton=window.formbutton||function(){(formbutton.q=formbutton.q||[]).push(arguments)};
                formbutton("create", {
                    action: "https://formspree.io/{your-form-id}",
                    title: "How can we help?",
                    fields: [
                    { 
                        type: "email", 
                        label: "Email:", 
                        name: "email",
                        required: true,
                        placeholder: "your@email.com"
                    },
                    {
                        type: "textarea",
                        label: "Message:",
                        name: "message",
                        placeholder: "What would you like to discuss?",
                    },
                    { type: "submit" }      
                ],
                styles: {
                    title: {
                        backgroundColor: "#ff7b24"
                    },
                    button: {
                        backgroundColor: "#ff7b24"
                    }
                }
                });`
            }}
        />
    ]);
};
Enter fullscreen mode Exit fullscreen mode

Adding this to the page resulted in a small button on the site that the user can click to send a form to the user!
image

Discussion (0)