NextJS Forms

SirenaAlyce
SirenaAlyce

Created At: March 19th, 2022

Updated At: March 20th, 2022

Forms are everywhere! You will almost always have to include a form or form function in your projects. A form has a client-server relationship, where the client is the form or what a user interacts with, while the server is what and where the data from the form is sent to, stored and retrieved - also called storage. NextJS lets developers handle both client and server-side development. In this video, I will show you how to build a form with NextJS, React Hook Forms, and Yup. I will also be showing you how to send data to an API endpoint using NextJS.

For the full tutorial, check out my video here:

Here is the source code:

/pages/Contact.js

import React from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { useRouter } from "next/router";

export default function Contact() {
  const router = useRouter();
  const schema = yup
    .object({
      firstName: yup.string().required().max(3),
      lastName: yup.string().required().max(100),
      Email: yup.string().required().email(),
      Message: yup.string().required(),
    })
    .required();

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({ resolver: yupResolver(schema) });

  const onSubmit = (data) => {
    fetch("/api/formdata", {
      method: "POST",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(data),
    });
    alert(`is this your name: ${data.firstName}`);
    router.push("/thankyou");
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {console.log(errors)}
      <input
        type="text"
        placeholder="First name"
        {...register("firstName")}
        id="first"
        name="firstName"
      />
      {errors.firstName?.message}
      <input
        type="text"
        placeholder="Last name"
        id="last"
        {...register("lastName")}
        name="lastName"
      />
      {errors.lastName?.message}
      <input
        type="email"
        placeholder="Email"
        id="email"
        {...register("Email")}
        name="Email"
      />
      {errors.Email?.message}
      <input
        type="textarea"
        placeholder="Message"
        id="message"
        {...register("Message")}
        name="Message"
      />
      {errors.Message?.message}
      <button type="submit">Submit</button>
    </form>
  );
}

/pages/index.js

import Contact from "./contact";

export default function Home() {
  return (
    <div>
      <Contact />
    </div>
  );
}

/pages/api/formdata.js

export default function handler(req, res) {
    const body = req.body

    console.log('body: ', body)

    if (!body.firstName || !body.lastName) {
        return res.status(400).json({ data: 'first or last name not found'})
    }

    res.status(200).json({ data: `${body.firstName} ${body.lastName}`})
}

/pages/thankyou.js

export default function Thanks() {
  return <div>Thank You!</div>;
}

Let's Connect!

Be sure to subscribe to my YouTube Channel!

Get social with me on IG @sirenaalyce.io.

Be inspired.

Be encouraged.

Be confident.

Back to Blog Home
© 2021 Sirena Alyce, LLC.