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-projectnpx create-next-app@latest .
npm run devUse 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.
1const FORM_ENDPOINT = 'https://herotofu.com/start'; // TODO - update to the correct endpoint
2
3function ContactForm() {
4 return (
5 <div className="md:w-96 md:max-w-full w-full mx-auto">
6 <div className="sm:rounded-md p-6 border border-gray-300">
7 <form method="POST" action={FORM_ENDPOINT}>
8 <label className="block mb-6">
9 <span className="text-gray-700">Your name</span>
10 <input
11 type="text"
12 name="name"
13 className=" focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 block w-full mt-1 border-gray-300 rounded-md shadow-sm"
14 placeholder="Joe Bloggs"
15 />
16 </label>
17 <label className="block mb-6">
18 <span className="text-gray-700">Email address</span>
19 <input
20 name="email"
21 type="email"
22 className=" focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 block w-full mt-1 border-gray-300 rounded-md shadow-sm"
23 placeholder="joe.bloggs@example.com"
24 required
25 />
26 </label>
27 <label className="block mb-6">
28 <span className="text-gray-700">Message</span>
29 <textarea
30 name="message"
31 className=" focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 block w-full mt-1 border-gray-300 rounded-md shadow-sm"
32 rows={3}
33 placeholder="Tell us what you're thinking about..."
34 ></textarea>
35 </label>
36 <div className="mb-2">
37 <button
38 type="submit"
39 className=" focus:shadow-outline hover:bg-indigo-800 h-10 px-5 text-indigo-100 transition-colors duration-150 bg-indigo-700 rounded-lg"
40 >
41 Contact Us
42 </button>
43 </div>
44 </form>
45 </div>
46 </div>
47 );
48}
49
50export default ContactForm;Once your static component is ready, let's write a custom hook that will handle your form submissions.
Add this function to the top of your file. Explore the code below to see how it works.
1function useContactForm() {
2 const [status, setStatus] = useState<string>();
3
4 const handleFormSubmit: React.FormEventHandler = (e) => {
5 e.preventDefault();
6 const form = e.currentTarget as HTMLFormElement;
7
8 const injectedData: Record<string, string | number> = {
9 // Here you can specify anything you need to inject dynamically, outside the form. For example:
10 // DYNAMIC_DATA_EXAMPLE: 123,
11 };
12
13 const inputs = Array.from(form.elements) as HTMLFormElement[];
14 const data = inputs
15 .filter((input) => input.name)
16 .reduce((obj, input) => Object.assign(obj, { [input.name]: input.value }), {} as Record<string, string>);
17
18 Object.assign(data, injectedData);
19
20 fetch(FORM_ENDPOINT, {
21 method: 'POST',
22 headers: {
23 Accept: 'application/json',
24 'Content-Type': 'application/json',
25 },
26 body: JSON.stringify(data),
27 })
28 .then((response) => {
29 // It's likely a spam/bot submission, so bypass it to validate via captcha challenge old-school style
30 if (response.status === 422) {
31 // Append dynamically generated keys back to the form
32 Object.keys(injectedData).forEach((key) => {
33 const el = document.createElement('input');
34 el.type = 'hidden';
35 el.name = key;
36 el.value = injectedData[key].toString();
37
38 form.appendChild(el);
39 });
40
41 // Let's submit the form again and spammer/bot will be redirected to another page automatically
42 // Submitting via javascript will bypass calling this function again
43 form.setAttribute('target', '_blank');
44 form.submit();
45
46 throw new Error('Please finish the captcha challenge');
47 }
48
49 if (response.status !== 200) {
50 throw new Error(response.statusText);
51 }
52
53 return response.json();
54 })
55 .then(() => setStatus("We'll be in touch soon."))
56 .catch((err) => setStatus(err.toString()));
57 };
58
59 return { status, handleFormSubmit };
60}
61
62// Here goes the rest of the code...Then, adjust the Form component to use the hook with new `status` and `handleFormSubmit` variables.
1function ContactForm() {
2 const { status, handleFormSubmit } = useContactForm();
3
4 if (status) {
5 return (
6 <div className="md:w-96 md:max-w-full w-full mx-auto">
7 <div className="sm:rounded-md p-6 border border-gray-300">
8 <div className="text-2xl">Thank you!</div>
9 <div className="text-md">{status}</div>
10 </div>
11 </div>
12 );
13 }
14
15 return (
16 <div className="md:w-96 md:max-w-full w-full mx-auto">
17 <div className="sm:rounded-md p-6 border border-gray-300">
18 <form method="POST" action={FORM_ENDPOINT} onSubmit={handleFormSubmit}>
19
20 // Here goes the rest of the code...Click here for a full code example with component and hook.
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).
1import ContactForm from '../components/ContactForm';
2
3function Page() {
4 return <ContactForm />;
5}
6
7export default Page;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.tsx file and fill in the form endpoint URL. You need to change the FORM_ENDPOINT variable at the top of the file. It should look like this.
1import React, { useState } from 'react';
2
3const FORM_ENDPOINT = 'https://public.herotofu.com/v1/EXAMPLE_FORM_ID';
4
5// Here goes the rest of the code...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 (codepen link here).
1import { useCallback, useState } from 'react';
2
3function useEmail(endpointUrl: string) {
4 const [submitted, setSubmitted] = useState(false);
5 const [loading, setLoading] = useState(false);
6 const [error, setError] = useState();
7
8 const sendEmail = useCallback(
9 (data: unknown) => {
10 setLoading(true);
11 setSubmitted(false);
12 setError(undefined);
13
14 fetch(endpointUrl, {
15 method: 'POST',
16 headers: {
17 Accept: 'application/json',
18 'Content-Type': 'application/json',
19 },
20 body: JSON.stringify(data),
21 })
22 .then((response) => {
23 // Endpoint thinks that it's likely a spam/bot request, you need to change "spam protection mode" to "never" in HeroTofu forms
24 if (response.status === 422) {
25 throw new Error('Are you robot?');
26 }
27
28 if (response.status !== 200) {
29 throw new Error(`${response.statusText} (${response.status})`);
30 }
31
32 return response.json();
33 })
34 .then(() => {
35 setSubmitted(true);
36 })
37 .catch((err) => {
38 setError(err.toString());
39 })
40 .finally(() => {
41 setLoading(false);
42 });
43 },
44 [endpointUrl]
45 );
46
47 return {
48 submitted,
49 loading,
50 error,
51 sendEmail,
52 };
53}
54
55export default useEmail;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.