useModalForm
The useModalForm
hook allows you to manage a form within a <Modal>
. It returns Ant Design <Form>
and Modal components props.
useModalForm
hook is extended from useForm
from the @refinedev/antd
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.
- create
- edit
- clone
In this example, we will show you how to create a record with useModalForm
.
Let's learn how to add editing capabilities to records that will be opening form in Modal by using the action
prop.
refine doesn't automatically add a <EditButton/>
to the each record in <PostList>
which opens the edit form in <Modal>
when clicked.
So, we have to put the <EditButton/>
on our list. In that way, <Edit>
form in <Modal>
can fetch data by the record id
.
<Table.Column<IPost>
title="Actions"
dataIndex="actions"
key="actions"
render={(_value, record) => <EditButton onClick={() => show(record.id)} />}
/>
Don't forget to pass the record "id"
to show
to fetch the record data. This is necessary for both "edit"
and "clone"
forms.
Let's learn how to add cloning capabilities to records that will be opening form in Modal by using the action
prop.
refine doesn't automatically add a <CloneButton/>
to the each record in <PostList>
which opens clone form in <Modal>
when clicked.
So, we have to put the <CloneButton/>
on our list. In that way, <Clone>
form in <Modal>
can fetch data by the record id
.
<Table.Column<IPost>
title="Actions"
dataIndex="actions"
key="actions"
render={(_value, record) => <CloneButton onClick={() => show(record.id)} />}
/>
Don't forget to pass the record id to show
to fetch the record data. This is necessary for both "edit"
and "clone"
forms.
Propertiesβ
All useForm
props are also available in useModalForm
. You can find descriptions on the useForm
documentation.
syncWithLocation
β
When syncWithLocation
is true
, the drawers visibility state and the id
of the record will be synced with the URL. It is false
by default.
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 },
});
defaultFormValues
β
defaultFormValues
is 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({
defaultFormValues: {
title: "Hello World",
},
});
defaultVisible
β
When defaultVisible
is true
, the modal will be visible by default. It is false
by default.
const modalForm = useModalForm({
defaultVisible: true,
});
autoSubmitClose
β
autoSubmitClose
will make the modal close after a successful submit. It is true
by default.
const modalForm = useModalForm({
autoSubmitClose: false,
});
autoResetForm
β
autoResetForm
will reset the form after a successful submit. It is true
by default.
const modalForm = useModalForm({
autoResetForm: false,
});
warnWhenUnsavedChanges
β
When set to true, warnWhenUnsavedChanges
shows a warning when the user tries to leave the page with unsaved changes. It is used to prevent the user from accidentally leaving the page. It is false
by default
You can also set this value in <Refine>
component.
const modalForm = useModalForm({
warnWhenUnsavedChanges: 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 } = useModalForm({
//...
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.
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
.
useModalForm({
autoSave: {
enabled: true,
},
})
debounce
β
Set the debounce time for the autoSave
prop. Default value is 1000
.
useModalForm({
autoSave: {
enabled: true,
debounce: 2000,
},
})
onFinish
β
If you want to modify the data before sending it to the server, you can use onFinish
callback function.
useModalForm({
autoSave: {
enabled: true,
onFinish: (values) => {
return {
foo: "bar",
...values,
};
},
},
})
Return Valuesβ
formProps
β
It's required to manage <Form>
state and actions. Under the hood the formProps
came from useForm
.
It contains the props to manage the Antd <Form>
components such as onValuesChange
, initialValues
, onFieldsChange
, onFinish
etc.
modalProps
β
The props needed by the <Modal>
component.
title
β
Default when url is
"/posts/create"
: "Create Post"
Title of the modal. Value is based on resource and action values.
okText
β
okText
is the text of the "submit"
button within the modal. It is "Save" by default.
cancelText
β
cancelText
is the text of the "cancel"
button within the modal. It is "Cancel" by default.
width
β
Width of the <Modal>
. It is 1000px
by default.
forceRender
β
forceRender
renders the <Modal>
instead of lazy rendering it. It is true
by default.
okButtonProps
β
okButtonProps
contains all the props needed by the "submit"
button within the modal (disabled,loading etc.). When okButtonProps.onClick
is called, it triggers form.submit()
. You can manually pass these props to your custom button.
onOk
β
A function that can submit the <Form>
inside <Modal>
. It's useful when you want to submit the form manually.
onCancel
β
Same as
close
A function that can close the <Modal>
. It's useful when you want to close the modal manually.
visible
deprecatedβ
visible
This prop is deprecated. Please use
open
instead.
Current visible state of <Modal>
. Default value depends on defaultVisible
prop.
open
β
Current visible state of <Modal>
. Default value depends on defaultVisible
prop.
close
β
Same as
onCancel
A function that can close the <Modal>
. It's useful when you want to close the modal manually.
const { close, modalProps, formProps, onFinish } = useModalForm();
const onFinishHandler = (values) => {
onFinish(values);
close();
};
// ---
return (
<Modal {...modalProps}>
<Form {...formProps} onFinish={onFinishHandler} layout="vertical">
<Form.Item label="Title" name="title">
<Input />
</Form.Item>
</Form>
</Modal>
);
submit
β
submit
is a function that can submit the form. It's useful when you want to submit the form manually.
const { modalProps, formProps, submit } = useModalForm();
// ---
return (
<Modal
{...modalProps}
footer={[
<Button key="submit" type="primary" onClick={submit}>
Submit
</Button>,
]}
>
<Form {...formProps} layout="vertical">
<Form.Item label="Title" name="title">
<Input />
</Form.Item>
</Form>
</Modal>
);
show
β
show
is a function that can show the modal.
const { modalProps, formProps, show } = useModalForm();
return (
<>
<Button type="primary" onClick={() => show()}>
Show Modal
</Button>
<Modal
{...modalProps}
footer={[
<Button key="submit" type="primary" onClick={submit}>
Submit
</Button>,
]}
>
<Form {...formProps} onFinish={onFinishHandler} layout="vertical">
<Form.Item label="Title" name="title">
<Input />
</Form.Item>
</Form>
</Modal>
</>
);
const { modalProps, formProps } = useModalForm();
// ---
return (
<Modal
{...modalProps}
footer={
<Button
onClick={(
e: React.MouseEvent<HTMLAnchorElement, MouseEvent> &
React.MouseEvent<HTMLButtonElement, MouseEvent>,
) => modalProps.onCancel(e)}
>
Cancel
</Button>
}
>
<Form {...formProps} layout="vertical">
<Form.Item label="Title" name="title">
<Input />
</Form.Item>
</Form>
</Modal>
);
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 } = useModalForm();
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?β
Here is an example where we modify the form data before submit:
We need to send the values we received from the user in two separate inputs, name
and surname
, to the API as fullName
.
import React from "react";
import { Modal, useModalForm } from "@refinedev/antd";
import { Form, Input } from "antd";
export const UserCreate: React.FC = () => {
const { formProps, modalProps } = useModalForm({
action: "create",
});
const handleOnFinish = (values) => {
formProps.onFinish?.({
fullName: `${values.name} ${values.surname}`,
});
};
return (
<Modal {...modalProps}>
<Form {...formProps} onFinish={handleOnFinish} layout="vertical">
<Form.Item label="Name" name="name">
<Input />
</Form.Item>
<Form.Item label="Surname" name="surname">
<Input />
</Form.Item>
</Form>
</Modal>
);
};
API Referenceβ
Propertiesβ
*
: These props have default values inRefineContext
and can also be set on <Refine> component.useModalForm
will use what is passed to<Refine>
as default but a local value will override it.
**
: If not explicitly configured, default value ofredirect
depends on whichaction
used. Ifaction
iscreate
,redirect
s default value isedit
(created resources edit page). Ifaction
isedit
instead,redirect
s default value islist
.
Type Parametersβ
Property | Desription | Type | Default |
---|---|---|---|
TQueryFnData | Result data returned by the query function. Extends BaseRecord | BaseRecord | BaseRecord |
TError | Custom error object that extends HttpError | HttpError | HttpError |
TVariables | Values for params. | {} | |
TData | Result data returned by the select function. Extends BaseRecord . If not specified, the value of TQueryFnData will be used as the default value. | BaseRecord | TQueryFnData |
TResponse | Result data returned by the mutation function. Extends BaseRecord . If not specified, the value of TData will be used as the default value. | BaseRecord | TData |
TResponseError | Custom error object that extends HttpError . If not specified, the value of TError will be used as the default value. | HttpError | TError |
Return Valueβ
Key | Description | Type |
---|---|---|
show | A function that can open the modal | (id?: BaseKey) => void |
formProps | Props needed to manage form component | FormProps |
modalProps | Props for needed to manage modal component | ModalProps |
formLoading | Loading status of form | boolean |
submit | Submit method, the parameter is the value of the form fields | () => void |
open | Whether the modal dialog is open or not | boolean |
close | Specify a function that can close the modal | () => void |
defaultFormValuesLoading | DefaultFormValues loading status of form | boolean |
form | Ant Design form instance | FormInstance<TVariables> |
id | Record id for edit action | BaseKey | undefined |
setId | id setter | Dispatch<SetStateAction< BaseKey | undefined>> |
queryResult | Result of the query of a record | QueryObserverResult<{ data: TData }> |
mutationResult | Result of the mutation triggered by submitting the form | UseMutationResult<{ data: TData }, TError, { resource: string; values: TVariables; }, unknown> |
overtime | Overtime loading props | { elapsedTime?: number } |
autoSaveProps | Auto save props | { data: UpdateResponse<TData> | undefined, error: HttpError | null, status: "loading" | "error" | "idle" | "success" } |
Exampleβ
npm create refine-app@latest -- --example form-antd-use-modal-form
- Basic Usage
- Properties
syncWithLocation
defaultFormValues
defaultVisible
autoSubmitClose
autoResetForm
warnWhenUnsavedChanges
overtimeOptions
autoSave
enabled
debounce
onFinish
- Return Values
formProps
modalProps
title
okText
cancelText
width
forceRender
okButtonProps
onOk
onCancel
visible
open
close
submit
show
overtime
autoSaveProps
- FAQ
- How can I change the form data before submitting it to the API?
- API Reference
- Properties
- Type Parameters
- Return Value
- Example