Creating a Form using React and NextJS App Router

janac
3 min readJan 9, 2024

To create a form in React v18+ and NextJS App Router, there is some prerequisite knowledge required.

Just a weird A.I. generated image for the prompt “form data” :)

Prerequisites

This article assumes that you already have the following knowledge:

React

  1. Specifically what components and state are.
  2. React Server Components

Next

  1. How Server Side Rendering works
  2. How to use React Server Components in NextJS
  3. How to use Client Components in NextJS
  4. How to interleave Server and Client Components

Shameless plug: Feel free to check my article that covers all of these NextJS prerequisites: React Server Components VS Client Components in NextJS App Router | by janac | Jan, 2024 | Medium

High-level Summary

  1. Create form elements such as text inputs, checkboxes etc., in a React Client Component
  2. Use the formAction attribute on a <form> to call a callback function that will receive the form data
  3. Put the callback function into it’s own module (file) with the annotation "use server"; — this makes the function a NextJS Server Action

Step 1: Create Form Elements

"use client";
import React from "react";
import { useFormState } from "react-dom";
import { action } from "../actions";
import SubmitButton from "./submit-button";

const initialState = {
message: '',
}

export default function MultiCheckbox() {
const formValuesMap: { [key: string]: boolean } = {
apple: false,
banana: true,
orange: false,
grape: false,
};

// "checkBoxKeys:" apple,banana,orange
const checkBoxKeys = Object.keys(formValuesMap);
const values = { ...formValuesMap }; // values:{"apple":false,"banana":true,"orange":false,"grape":false}
console.log("values:" + JSON.stringify(values));

const [state, formAction] = useFormState(action, initialState);

return (
<div>
<h1>Learning React!</h1>
<h2>Forms in React</h2>
<hr></hr>

<h3>Multiple Checkbox Form</h3>

<form>
<fieldset>
<legend>Pick a fruit, any fruit.</legend>…

--

--

janac

Most of my writing is about software. I enjoy summarizing and analyzing books and self-help videos. I am senior software consultant at LazerTechnologies.com.