Skip to main content
👀 Interested in the latest enterprise backend features of refine? 👉 Join now and get early access!
Version: 4.xx.xx

useDrawerForm

useModalForm hook allows you to manage a form within a <Modal> as well as a <Drawer>. It provides some useful methods to handle the form <Modal> or form <Drawer>.

We will use useModalForm hook as a useDrawerForm to manage a form within a <Drawer>.

INFORMATION

useDrawerForm hook is extended from useForm hook from the @refinedev/mantine package. This means that you can use all the features of useForm hook.

Basic Usage​

We'll show two examples, one for creating and one for editing a post. Let's see how useDrawerForm is used in both.

In this example, we will show you how to "create" a record with useDrawerForm.

localhost:3000/posts
import React from "react";
import { useTable } from "@refinedev/react-table";
import { ColumnDef, flexRender } from "@tanstack/react-table";
import { GetManyResponse, useMany } from "@refinedev/core";
import {
List,
useModalForm as useDrawerForm,
SaveButton,
} from "@refinedev/mantine";
import {
Box,
Group,
ScrollArea,
Table,
Pagination,
Drawer,
Select,
TextInput,
} from "@mantine/core";

const PostList: React.FC = () => {
const {
getInputProps,
saveButtonProps,
modal: { show, close, title, visible },
} = useDrawerForm({
refineCoreProps: { action: "create" },
initialValues: {
title: "",
status: "",
content: "",
},
validate: {
title: (value) => (value.length < 2 ? "Too short title" : null),
status: (value) =>
value.length <= 0 ? "Status is required" : null,
},
});

const columns = React.useMemo<ColumnDef<IPost>[]>(
() => [
{
id: "id",
header: "ID",
accessorKey: "id",
},
{
id: "title",
header: "Title",
accessorKey: "title",
meta: {
filterOperator: "contains",
},
},
{
id: "status",
header: "Status",
accessorKey: "status",
meta: {
filterElement: function render(props: FilterElementProps) {
return (
<Select
defaultValue="published"
data={[
{ label: "Published", value: "published" },
{ label: "Draft", value: "draft" },
{ label: "Rejected", value: "rejected" },
]}
{...props}
/>
);
},
filterOperator: "eq",
},
},
],
[],
);

const {
getHeaderGroups,
getRowModel,
setOptions,
refineCore: {
setCurrent,
pageCount,
current,
tableQueryResult: { data: tableData },
},
} = useTable({
columns,
});

return (
<>
<Drawer
opened={visible}
onClose={close}
title={title}
padding="xl"
size="xl"
position="right"
>
<TextInput
mt={8}
label="Title"
placeholder="Title"
{...getInputProps("title")}
/>
<Select
mt={8}
label="Status"
placeholder="Pick one"
data={[
{ label: "Published", value: "published" },
{ label: "Draft", value: "draft" },
{ label: "Rejected", value: "rejected" },
]}
{...getInputProps("status")}
/>
<Box
mt={8}
sx={{ display: "flex", justifyContent: "flex-end" }}
>
<SaveButton {...saveButtonProps} />
</Box>
</Drawer>
<ScrollArea>
<List createButtonProps={{ onClick: () => show() }}>
<Table highlightOnHover>
<thead>
{getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<th key={header.id}>
{!header.isPlaceholder && (
<Group spacing="xs" noWrap>
<Box>
{flexRender(
header.column
.columnDef
.header,
header.getContext(),
)}
</Box>
</Group>
)}
</th>
);
})}
</tr>
))}
</thead>
<tbody>
{getRowModel().rows.map((row) => {
return (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => {
return (
<td key={cell.id}>
{flexRender(
cell.column.columnDef
.cell,
cell.getContext(),
)}
</td>
);
})}
</tr>
);
})}
</tbody>
</Table>
<br />
<Pagination
position="right"
total={pageCount}
page={current}
onChange={setCurrent}
/>
</List>
</ScrollArea>
</>
);
};

interface IPost {
id: number;
title: string;
status: "published" | "draft" | "rejected";
}

Properties​

refineCoreProps​

All useForm properties also available in useStepsForm. You can find descriptions on useForm docs.

const drawerForm = useDrawerForm({
refineCoreProps: {
action: "edit",
resource: "posts",
id: "1",
},
});

initialValues​

Only available in "create" form.

Default values for the form. Use this to pre-populate the form with data that needs to be displayed.

const drawerForm = useDrawerForm({
initialValues: {
title: "Hello World",
},
});

defaultVisible​

Default: false

When true, drawer will be visible by default.

const drawerForm = useDrawerForm({
modalProps: {
defaultVisible: true,
},
});

autoSubmitClose​

Default: true

When true, drawer will be closed after successful submit.

const drawerForm = useDrawerForm({
modalProps: {
autoSubmitClose: false,
},
});

autoResetForm​

Default: true

When true, form will be reset after successful submit.

const drawerForm = useDrawerForm({
modalProps: {
autoResetForm: false,
},
});

syncWithLocation​

Default: false

When true, the drawers visibility state and the id of the record will be synced with the URL.

This property can also be set as an object { key: string; syncId?: boolean } to customize the key of the URL query parameter. id will be synced with the URL only if syncId is true.

const drawerForm = useDrawerForm({
syncWithLocation: { key: "my-modal", syncId: true },
});

overtimeOptions​

If you want loading overtime for the request, you can pass the overtimeOptions prop to the this hook. It is useful when you want to show a loading indicator when the request takes too long. interval is the time interval in milliseconds. onInterval is the function that will be called on each interval.

Return overtime object from this hook. elapsedTime is the elapsed time in milliseconds. It becomes undefined when the request is completed.

const { overtime } = useDrawerForm({
//...
overtimeOptions: {
interval: 1000,
onInterval(elapsedInterval) {
console.log(elapsedInterval);
},
}
});

console.log(overtime.elapsedTime); // undefined, 1000, 2000, 3000 4000, ...

// You can use it like this:
{elapsedTime >= 4000 && <div>this takes a bit longer than expected</div>}

autoSave​

If you want to save the form automatically after some delay when user edits the form, you can pass true to autoSave.enabled prop.

It also supports onMutationSuccess and onMutationError callback functions. You can use isAutoSave parameter to determine whether the mutation is triggered by autoSave or not.

CAUTION

Works only in action: "edit" mode.

onMutationSuccess and onMutationError callbacks will be called after the mutation is successful or failed.

enabled​

To enable the autoSave feature, set the enabled parameter to true.

useDrawerForm({
refineCoreProps: {
autoSave: {
enabled: true,
},
}
})

debounce​

Set the debounce time for the autoSave prop. Default value is 1000.

useDrawerForm({
refineCoreProps: {
autoSave: {
enabled: true,
debounce: 2000,
},
}
})

Return Values​

TIP

All useForm return values also available in useDrawerForm. You can find descriptions on useForm docs.

All mantine useForm return values also available in useDrawerForm. You can find descriptions on mantine docs.

visible​

Current visibility state of the drawer.

const drawerForm = useDrawerForm({
defaultVisible: true,
});

console.log(drawerForm.modal.visible); // true

title​

Title of the drawer. Based on resource and action values

const {
modal: { title },
} = useDrawerForm({
refineCoreProps: {
resource: "posts",
action: "create",
},
});

console.log(title); // "Create Post"

close​

A function that can close the drawer. It's useful when you want to close the drawer manually.

const {
getInputProps,
modal: { close, visible, title },
} = useDrawerForm();

return (
<Drawer opened={visible} onClose={close} title={title}>
<TextInput
mt={8}
label="Title"
placeholder="Title"
{...getInputProps("title")}
/>
<Box mt={8} sx={{ display: "flex", justifyContent: "flex-end" }}>
<SaveButton {...saveButtonProps} />
<Button onClick={close}>Cancel</Button>
</Box>
</Drawer>
);

submit​

A function that can submit the form. It's useful when you want to submit the form manually.

const {
modal: { submit },
} = useDrawerForm();

// ---

return (
<Drawer opened={visible} onClose={close} title={title}>
<TextInput
mt={8}
label="Title"
placeholder="Title"
{...getInputProps("title")}
/>
<Box mt={8} sx={{ display: "flex", justifyContent: "flex-end" }}>
<Button onClick={submit}>Save</Button>
</Box>
</Drawer>
);

show​

A function that can show the drawer.

const {
getInputProps,
modal: { close, visible, title, show },
} = useDrawerForm();

const onFinishHandler = (values) => {
onFinish(values);
show();
};

return (
<>
<Button onClick={}>Show Modal</Button>
<Drawer opened={visible} onClose={close} title={title}>
<TextInput
mt={8}
label="Title"
placeholder="Title"
{...getInputProps("title")}
/>
<Box mt={8} sx={{ display: "flex", justifyContent: "flex-end" }}>
<SaveButton {...saveButtonProps} />
</Box>
</Drawer>
</>
);

saveButtonProps​

It contains all the props needed by the "submit" button within the drawer (disabled,loading etc.). You can manually pass these props to your custom button.

const { getInputProps, modal, saveButtonProps } = useDrawerForm();

return (
<Drawer {...modal}>
<TextInput
mt={8}
label="Title"
placeholder="Title"
{...getInputProps("title")}
/>
<Box mt={8} sx={{ display: "flex", justifyContent: "flex-end" }}>
<Button
{...saveButtonProps}
onClick={(e) => {
// -- your custom logic
saveButtonProps.onClick(e);
}}
/>
</Box>
</Drawer>
);

overtime​

overtime object is returned from this hook. elapsedTime is the elapsed time in milliseconds. It becomes undefined when the request is completed.

const { overtime } = useDrawerForm();

console.log(overtime.elapsedTime); // undefined, 1000, 2000, 3000 4000, ...

autoSaveProps​

If autoSave is enabled, this hook returns autoSaveProps object with data, error, and status properties from mutation.

FAQ​

How can I change the form data before submitting it to the API?​

You may need to modify the form data before it is sent to the API.

For example, Let's send the values we received from the user in two separate inputs, name and surname, to the API as fullName.

pages/user/create.tsx
import React from "react";
import { useDrawerForm } from "@refinedev/mantine";
import { TextInput, Drawer } from "@mantine/core";

const UserCreate: React.FC = () => {
const {
getInputProps,
saveButtonProps,
modal: { show, close, title, visible },
} = useDrawerForm({
refineCoreProps: { action: "create" },
initialValues: {
name: "",
surname: "",
},
transformValues: (values) => ({
fullName: `${values.name} ${values.surname}`,
}),
});

return (
<Drawer opened={visible} onClose={close} title={title}>
<TextInput
mt={8}
label="Name"
placeholder="Name"
{...getInputProps("name")}
/>
<TextInput
mt={8}
label="Surname"
placeholder="Surname"
{...getInputProps("surname")}
/>
<Box mt={8} sx={{ display: "flex", justifyContent: "flex-end" }}>
<Button
{...saveButtonProps}
onClick={(e) => {
// -- your custom logic
saveButtonProps.onClick(e);
}}
/>
</Box>
</Drawer>
);
};

API Reference​

Properties​

PropertyDescriptionType
modalPropsConfiguration object for the modal or drawerModalPropsType
refineCorePropsConfiguration object for the core of the useFormUseFormProps
@mantine/form's useForm propertiesSee useForm documentation

PropertyDescriptionTypeDefault
defaultVisibleInitial visibility state of the modalbooleanfalse
autoSubmitCloseWhether the form should be submitted when the modal is closedbooleantrue
autoResetFormWhether the form should be reset when the form is submittedbooleantrue

Type Parameters​

PropertyDesriptionTypeDefault
TQueryFnDataResult data returned by the query function. Extends BaseRecordBaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpErrorHttpError
TVariablesForm values for mutation function{}Record<string, unknown>
TTransformedForm values after transformation for mutation function{}TVariables
TDataResult data returned by the select function. Extends BaseRecord. If not specified, the value of TQueryFnData will be used as the default value.BaseRecordTQueryFnData
TResponseResult data returned by the mutation function. Extends BaseRecord. If not specified, the value of TData will be used as the default value.BaseRecordTData
TResponseErrorCustom error object that extends HttpError. If not specified, the value of TError will be used as the default value.HttpErrorTError

Return values​

PropertyDescriptionType
modalRelevant states and methods to control the modal or drawerModalReturnValues
refineCoreThe return values of the useForm in the coreUseFormReturnValues
@mantine/form's useForm return valuesSee useForm documentation
overtimeOvertime loading props{ elapsedTime?: number }

PropertyDescriptionType
visibleState of modal visibilityboolean
showSets the visible state to true(id?: BaseKey) => void
closeSets the visible state to false() => void
submitSubmits the form(values: TVariables) => void
titleModal title based on resource and action valuestring
saveButtonPropsProps for a submit button{ disabled: boolean, onClick: (e: React.FormEvent<HTMLFormElement>) => void; }

Example​

Run on your local
npm create refine-app@latest -- --example form-mantine-use-drawer-form
Last updated on Jul 19, 2023 by Yıldıray Ünlü