Skip to main content

Working with forms

Forms are an essential part of interactive websites and applications. It lets users submit information through various input or select elements.

To create a form, we use the <Form> component of Next.js. This is an extension of the HTML <form> element, so it has the exact same functionality plus something extra.

<Form action={createCalendarEvent}>
<input name="client" required type="text" />
<button type="submit">Add</button>
</Form>

In the example above you see a basic template of what a form would look like. The form has an action attribute, which is used to specify which action should be taken upon submission. The submission of the form is triggered when the button is clicked due to its type="submit".

const createCalendarEvent = async (formData: FormData): Promise<void> => {
'use server';
const client = formData.get('client');

console.log('client:', client);
}

The function that should be invoked upon submission you have to define yourself. By nature the function assigned to the <form>'s action attribute, receives formData as an argument. As shown in the example, we need to perform the .get() method to be able to extract the value from a key/value pair of the formData. We provide the 'use server' directive to the function to explicitly state that this function should be a Server Function. Essentially this means that this form can be submitted without JavaScript enabled in the browser, because all the logic is prebuilt on the server.

Further reading