HTML Anchor link to section titled "HTML form element"
Form component builds on the native HTML
<form> element. The following is an example:
POST request to
/login with each form field encoded. The browser also reloads the entire page to display the server's response. Learn more about native HTML forms.
Hydrogen Anchor link to section titled "Hydrogen Form component"
Form component mimics the functionality of a native
The following example rewrites the example form element by substituting the native HTML with a
Form component that's imported from Hydrogen:
Anchor link to section titled "Form requires an API route"
Form requires an API route
action attribute must point to an API route. The following is an example implementation:
Read data in the API route from the
Form by using the
FormData API. The API route must respond with a
new Request(). This renders the server components for the given page. You can re-render the current page, or render an entirely different page in the app.
In the previous example, when the user is not found, the current page is re-rendered with an error set on the session. The following code updates the server component to render the login error:
The page initially loads without a session
loginError value. If the login mutation fails, then the server components re-render with the
loginError session value and display a message to the user. Because the component uses
useFlashSession instead of
useSession, the value is subsequently cleared. If the user refreshes the page, then the validation error goes away.
Client validation and feedbackAnchor link to section titled "Client validation and feedback"
The examples provided so far have been entirely in server components. However, the best user experience has client-side validation and gives user feedback while the form is submitting. This requires a client component.
The following example moves
Form into a client component:
Form is now within a client component,
children can be a render prop. This enables you to give users feedback while the form is submitting.
Hidden fieldsAnchor link to section titled "Hidden fields"
You can use the
Form component for any mutation that doesn't include a text field.
For example, the following uses a
Form component for adding items an item to a cart:
The hidden input field for the
productId is sent to the server when the Add to cart button is clicked. The API route at
Related componentsAnchor link to section titled "Related components"
Related framework topicsAnchor link to section titled "Related framework topics"
- Learn more about forms and API routes.