This guide will show you how to make a nice-looking and elegant form with NextJS, Tailwind CSS, and TypeScript. It works perfectly with standard NextJS pages and the new app directory, but can be used on standalone React too.
On top of that, your form will be able to handle spam submissions, send emails, and sync with your CRM/database.
In case you're starting a brand new project, you'll need some initial steps. One of the most straightforward ways is to use the create-next-app package. To start:
mkdir ~/nextjs-project && cd ~/nextjs-project
npx create-next-app@latest .
npm run dev
Use your favorite code editor to work with files in ~/nextjs-project. You will be able to make a contact form there.
Create a new file called ContactForm.tsx in the src/components/ folder. You can copy-paste the code below to get started quickly. Check HeroTofu's extensive forms library for other ready to use forms.
To effortlessly handle form submissions, you can use the herotofu-react package. It will do all the form submission process work for you.
Then, adjust the Form component to use the hook with new `formState` and `getFormSubmitHandler`.
Open any page you want to see the form and insert the newly created form component. It will work for old pages and the new app directory (don't forget the "use client" directive if using app directory).
Head over to herotofu.com and create an account. It will handle all the boring and complex form submission process work for you. You'll get 14 days of the free trial at first, and later you can leave it with the free forever plan. For vast majority of people, free plan is usually more than enough.
HeroTofu registration is straightforward. Fill in the basic fields and then confirm your email address.
Once you have confirmed your email address, go to app.herotofu.com/forms to create your first form. Fill in the form name and add your preferred email address where you'd like to receive your form submits. Slack and Zapier are also options, but you need to pay for them once the trial is over.
You'll get the form endpoint URL once you hit submit, so remember to copy it.
Once again, open the ContactForm.js file and fill in the form endpoint URL. You need to change the passed string to the useFormData() at the top of the component. It should look like this.
Done! Go ahead and test your form submission! You don't need to do any backend email work, as HeroTofu will handle everything.
HeroTofu accepts regular form submissions, multipart file uploads, and JSON payloads. So you can create javascript objects and send them via fetch() to the endpoint. When you send a JSON payload, don't forget to set the correct JSON headers, and HeroTofu will respond with the needed status codes. Here's what it could look like in practice.
Treat it as a REST API because as long as you're sending POST, you'll be good to go. Your react form submission will reach your inbox.