Skip to main content

CartForm

Creates a form for managing cart operations. Use CartActionInput to accept form inputs of known type.

Anchor to CartActionInputProps

CartActionInputProps

| | | | | | | | | | | | | | | | | |
Anchor to children
children
ReactNode | ((fetcher: FetcherWithComponents<any>) => ReactNode)
required

Children nodes of CartForm. Children can be a render prop that receives the fetcher.

Anchor to fetcherKey
fetcherKey
string

Optional key to use for the fetcher.

Anchor to route
route
string

The route to submit the form to. Defaults to the current route.

Examples
import {data} from 'react-router';
import {CartForm} from '@shopify/hydrogen';
import invariant from 'tiny-invariant';

export default function Cart() {
return (
<CartForm
action={CartForm.ACTIONS.LinesUpdate}
inputs={{
lines: [
{
id: 'gid://shopify/CartLine/123456789',
quantity: 3,
},
],
other: 'data',
}}
>
<button>Quantity up</button>
</CartForm>
);
}

export async function action({request, context}) {
const {cart} = context;

const formData = await request.formData();
const {action, inputs} = CartForm.getFormInput(formData);

let status = 200;
let result;

if (action === CartForm.ACTIONS.LinesUpdate) {
result = await cart.updateLines(inputs.lines);
} else {
invariant(false, `${action} cart action is not defined`);
}

const headers = cart.setCartId(result.cart.id);

return data(result, {status, headers});
}
Was this page helpful?