Skip to main content
Version: 4.xx.xx

useModalForm

useModalForm hook also allows you to manage a form inside a modal component. It provides some useful methods to handle the form modal.

info

useModalForm 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 three examples, "create", "edit" and "clone". Let's see how useModalForm is used in all.

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

http://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, SaveButton } from "@refinedev/mantine";
import {
Box,
Group,
ScrollArea,
Table,
Pagination,
Modal,
Select,
TextInput,
} from "@mantine/core";

const PostList: React.FC = () => {
const {
getInputProps,
saveButtonProps,
modal: { show, close, title, visible },
} = useModalForm({
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 (
<>
<Modal opened={visible} onClose={close} title={title}>
<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>
</Modal>
<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 modalForm = useModalForm({
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 modalForm = useModalForm({
initialValues: {
title: "Hello World",
},
});

defaultVisible

Default: false

When true, modal will be visible by default.

const modalForm = useModalForm({
modalProps: {
defaultVisible: true,
},
});

autoSubmitClose

Default: true

When true, modal will be closed after successful submit.

const modalForm = useModalForm({
modalProps: {
autoSubmitClose: false,
},
});

autoResetForm

Default: true

When true, form will be reset after successful submit.

const modalForm = useModalForm({
modalProps: {
autoResetForm: false,
},
});

syncWithLocation

Default: false

When true, the modals 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 modalForm = useModalForm({
syncWithLocation: { key: "my-modal", syncId: true },
});

Return Values

tip

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

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

visible

Current visibility state of the modal.

const modalForm = useModalForm({
defaultVisible: true,
});

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

title

Title of the modal. Based on resource and action values

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

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

close

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

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

return (
<Modal 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>
</Modal>
);

submit

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

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

// ---

return (
<Modal 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>
</Modal>
);

show

A function that can show the modal.

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

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

return (
<>
<Button onClick={}>Show Modal</Button>
<Modal 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>
</Modal>
</>
);

saveButtonProps

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

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

return (
<Modal {...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>
</Modal>
);

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

  • ModalPropsType

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

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

  • ModalReturnValues

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 IN YOUR LOCAL
npm create refine-app@latest -- --example form-mantine-use-modal-form