0
0
NextJSframework~30 mins

Form actions with server functions in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Form actions with server functions
📖 Scenario: You are building a simple contact form on a website. When a user submits their name and message, the form should send this data to the server to be processed.
🎯 Goal: Create a Next.js form that uses a server function to handle form submission and display a confirmation message.
📋 What You'll Learn
Create a form with name and message input fields
Create a server function called sendMessage to handle the form data
Use the form element with the action attribute set to the server function
Display a confirmation message after the form is submitted
💡 Why This Matters
🌍 Real World
Forms are everywhere on websites for collecting user input like contact info, feedback, or orders. Handling form submissions on the server securely processes and stores this data.
💼 Career
Understanding how to connect frontend forms with backend server functions is essential for full-stack web development roles, especially when using modern frameworks like Next.js.
Progress0 / 4 steps
1
Create the form data structure
Create a React functional component called ContactForm with a form element containing two input fields: name (type text) and message (textarea). Include a submit button with the text Send.
NextJS
Need a hint?

Use a form element with input and textarea inside the ContactForm component.

2
Add the server function to handle form submission
Create an async server function called sendMessage that accepts a FormData object as a parameter. Extract the name and message values from the form data inside this function.
NextJS
Need a hint?

Use formData.get('name') and formData.get('message') to get the values.

3
Connect the form to the server function
Modify the form element inside ContactForm to use the sendMessage server function as its action attribute.
NextJS
Need a hint?

Set the action attribute of the form to {sendMessage}.

4
Complete the server function with a confirmation message
Inside the sendMessage server function, add a return statement that returns a React fragment with a p element. The p element should contain the text: Thank you, {name}, your message has been sent! using the extracted name variable.
NextJS
Need a hint?

Return a React element with the thank you message using the name variable.