Build an Advanced Contact Form in React with Nodemailer

Build an Advanced Contact Form in React with Nodemailer

A contact form allows website visitors to send messages, but you can make it more useful with validation, error handling, and email integration. In this 2023 updated tutorial, I’ll show you how to build an advanced React contact form integrated with Nodemailer to email submissions to yourself.

Overview

Here’s what our contact form will do:

  • Accept name, email, subject, and message inputs
  • Validate fields to ensure proper inputs
  • Display error messages for invalid fields
  • Send an email with form data to your email
  • Display success or error message after submitting
  • Reset to initial state after submit

We’ll use the latest version of React for the frontend form and Nodemailer for sending emails from the Express backend.

Use Cases

This contact form has a variety of use cases:
Business Website
Add to a “Contact Us” page so potential customers can inquire about your business. Email questions directly to your sales team.
Support Site
Include on a SaaS app support site for users to report issues or ask for help. Messages go to your support team mailbox.
Landing Pages
Embed on a landing page to capture leads. Add name and email validation to gather more info on signups.
The built-in validation and spam filtering also improve the quality of submissions by preventing bogus form entries. With the Nodemailer backend, messages safely reach the appropriate team’s email, ready to respond to users.
With some styling customizations, this form can fit seamlessly into any site to accept visitor messages. Try integrating it into your projects!

Set Up React App

Create a React app:

npx create-react-app my-contact-form
cd my-contact-form
npm start

Build the contact form component in App.js:

  • Custom hooks to manage form state
  • Input change handlers to update the state
  • Validation and error messaging
  • Handle form submission with Axios ## Create the Form UI

Design the form UI with:

  • Name, Email, Subject, Message inputs
  • Submit button

Use a custom hook to initialize and manage state:


    function useForm() {
      const [name, setName] = useState('');

      // input change handler
      const handleNameChange = e => {
        setName(e.target.value);
      }

      // additional form state and handlers

      return {
         name,
         handleNameChange
        // ...
      };
    }

Add Validation

To validate:

  • Check required fields are not empty
  • Validate email format

Show error message if invalid:

    {errors.name && <p>Name required</p>} 

Add logic to check the validity of input change and submit. Clear errors when fixed.

Submit Form Data

Submit handler:

  • Prevent default event
  • Check the form validity
  • POST data to API endpoint
    const submitForm = async e => {
      e.preventDefault();

      if(isValid) {
        try {
          await axios.post('/api/contact', {
            name, 
            email  
          });
          showSuccess();
        } catch(err) {
          showError();
        }
      } 
    }

Nodemailer Backend

Install Express, Nodemailer, and middlewares:

npm install express nodemailer cors dotenv

Configure credentials and transporter:

    const transporter = nodemailer.createTransport({
      service: 'Gmail',
      auth: { 
        user: process.env.EMAIL,
        pass: process.env.PASSWORD
      }
    });

POST route to send mail:

    app.post('/api/contact', (req, res) => {
      const { name, email, message } = req.body;

      const mailOptions = {
        from: name + ' <' + email + '>',
        replyTo: email,
        // email fields
      };

      transporter.sendMail(mailOptions, (err, data) => {
        // return response
      });
    });

Display Submission Messages

Handle success and error API responses in React.
On success:

  • Show a “Thank you” message
  • Clear form state

On error:

  • Show the “Error – please try again” message
    {message && <p>{message}</p>}

    <button onClick={clearMessage}>Ok</button> 

And we have an advanced, validated contact form integrated with email!
Some ideas for future improvement:

  • Additional field validation
  • Captcha/spam filtering
  • Save messages to a database
  • Automated confirmation email reply

Conclusion

In this tutorial, we built an advanced React contact form with validation and integrated email capabilities using Nodemailer.
Some key points:

  • The form accepts user name, email, subject, and message inputs
  • Client and server-side validation ensure correct user inputs
  • Submitted messages are emailed to you via Nodemailer transporter
  • Users see success/error messages after form submission
  • Everything resets after the message is sent

Overall, this creates a smooth contact form experience for visitors to contact you while validating info and directly sending messages to your email inbox.

If you like my work and want to help me continue dropping content like this, buy me a cup of coffee.

If you find this post exciting, find more exciting posts on Learnhub Blog; we write everything tech from Cloud computing to Frontend DevCybersecurityAI, and Blockchain.

Resource

1 thought on “Build an Advanced Contact Form in React with Nodemailer”

  1. you are truly a just right webmaster The site loading speed is incredible It kind of feels that youre doing any distinctive trick In addition The contents are masterwork you have done a great activity in this matter

Leave a Comment

Your email address will not be published. Required fields are marked *