Next.js - Form Component
Next.js - Form Component
Syntax
Following code shows syntax for basic usage of <Form> component in Next.js.
https://www.tutorialspoint.com/nextjs/nextjs_form_component.htm 1/7
Page 2 of 7
Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.
When the value action prop is a string, the <form> behaves like a native HTML form that
uses a GET method. The form data is encoded into the URL as search params, and when
the form is submitted. When action is a function (Server Action), the <form> behaves
like a React form. It will execute the action when the form is submitted.
Example
In the following code, we created a simple form in Next.js. When user click submit
button, form-submission page will be opened.
Output
https://www.tutorialspoint.com/nextjs/nextjs_form_component.htm 2/7
Page 3 of 7
The image below shows output of above code. Here you can see that after submitting
form, the form-submission page is opened.
Example
In the below code, after submitting form user will be redirected to form-submission page
and prevent moving back to form page.
https://www.tutorialspoint.com/nextjs/nextjs_form_component.htm 3/7
Page 4 of 7
)
}
Output
The image below shows output of above code. Here you can see that after submitting
form, navigation back to form page is prevented.
Example
In the below code, we added a top margin, so that form element become scrollable.
After submitting form the page will not scroll to top.
https://www.tutorialspoint.com/nextjs/nextjs_form_component.htm 4/7
Page 5 of 7
scroll={false}
style={{ marginTop: '700px' }}>
<input type="text" name="example" />
<button type="submit">Submit</button>
</Form>
)
}
Output
The image below shows output of above code. Here you can see that after submitting
form, the page is not scrolled to top.
https://www.tutorialspoint.com/nextjs/nextjs_form_component.htm 5/7
Page 6 of 7
default, Next.js prefetches routes when they appear in the users's viewport, so that the
subsequent navigation become instantaneous. Setting the prefetch prop to false disables
this behavior. This prop is valid only if the value of action prop is a string.
Example
In the below code, we added prefetch prop to form element. When user scroll to form
element, the form submission page will be prefetched.
Output
The image below shows output of above code. Here you can see that before submitting
form, the form-submission page is prefetched in networks tab on browser Dev tools.
https://www.tutorialspoint.com/nextjs/nextjs_form_component.htm 6/7
Page 7 of 7
https://www.tutorialspoint.com/nextjs/nextjs_form_component.htm 7/7