⌘I

Creare un modulo di contatto con React

Updated July 14, 2023

Scopri come creare un modulo React per raccogliere gli invii di un modulo di contatto e ricevere notifiche via email.

1. Prepara il tuo progetto

Installa la libreria helper per React nel tuo progetto:

npm install @formspree/react

Poi aggiungi il FormspreeProvider al componente principale della tua app. Per esempio, se usi Next.js, ecco come potrebbe apparire il tuo file pages/_app.js:

import { FormspreeProvider } from '@formspree/react';
function App({ Component, pageProps }) {
  return (
  	<FormspreeProvider project="{your-project-id}">
      <Component {...pageProps} />
    </FormspreeProvider>
  );
}
export default App;

2. Configura il tuo modulo

Nel tuo file formspree.json, aggiungi un modulo con un’azione che ti invii una notifica via email:

{
  "forms": {
    "contactForm": {
      "name": "Contact Form",
      "actions": [{ "type": "email", "to": "{your-email-address}" }]
    }
  }
}

Poi, distribuisci le tue modifiche su Formspree:

formspree deploy -k <your-deploy-key>

3. Crea il tuo modulo

Collega il componente del tuo modulo usando l’hook useForm:

import React from 'react';
import { useForm, ValidationError } from '@formspree/react';

function ContactForm() {
  const [state, handleSubmit] = useForm("contactForm");
  if (state.succeeded) {
      return <p>Thanks for joining!</p>;
  }
  return (
      <form onSubmit={handleSubmit}>
      <label htmlFor="email">
        Email Address
      </label>
      <input
        id="email"
        type="email" 
        name="email"
      />
      <ValidationError 
        prefix="Email" 
        field="email"
        errors={state.errors}
      />
      <textarea
        id="message"
        name="message"
      />
      <ValidationError 
        prefix="Message" 
        field="message"
        errors={state.errors}
      />
      <button type="submit" disabled={state.submitting}>
        Submit
      </button>
    </form>
  );
}
export default ContactForm;

Scopri di più sulla CLI di Formspree
Scopri di più su Formspree e React