0
0
NextJSframework~30 mins

Server action in client components in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Server Actions in Next.js Client Components
📖 Scenario: You are building a simple feedback form on a website. Users can type their feedback and submit it. The feedback should be sent to the server to be saved.
🎯 Goal: Create a Next.js client component that uses a server action to handle form submission and save feedback.
📋 What You'll Learn
Create a client component with a form and a textarea input named feedback.
Create a server action function called saveFeedback that accepts the feedback text.
Use the server action in the client component to handle the form submission.
Show a confirmation message after successful submission.
💡 Why This Matters
🌍 Real World
Collecting user feedback or form data on websites using Next.js with server actions for efficient server communication.
💼 Career
Understanding server actions in Next.js client components is important for building modern, scalable web applications with seamless server-client integration.
Progress0 / 4 steps
1
Create the client component with a feedback form
Create a React client component called FeedbackForm with a form containing a textarea input named feedback and a submit button. Add the directive 'use client' at the top.
NextJS
Need a hint?

Remember to add 'use client' at the top to make this a client component. Use a form with a textarea named feedback and a submit button.

2
Create the server action to save feedback
Create an async server action function called saveFeedback that accepts a parameter text. Inside, simulate saving by returning true. Export this function.
NextJS
Need a hint?

Create an async function named saveFeedback that takes text and returns true. Export it so it can be used as a server action.

3
Use the server action in the client component form
Import the saveFeedback server action into the client component. Add a form action attribute that calls saveFeedback. Use FormData to get the feedback value inside saveFeedback.
NextJS
Need a hint?

Change saveFeedback to accept formData. Use formData.get('feedback') to get the text. Set the form's action attribute to saveFeedback.

4
Show confirmation message after submission
Add a React state variable submitted initialized to false. After the server action completes, set submitted to true. Conditionally render a p tag with the text Thank you for your feedback! when submitted is true.
NextJS
Need a hint?

Use useState to track submission. Create a handleSubmit function that calls saveFeedback and then sets submitted to true. Show a thank you message when submitted.