Skip to main content
Version: 4.xx.xx

useModalForm

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

useModalForm hook is extended from useForm from the @refinedev/react-hook-form package. This means that you can use all the features of useForm hook.

Usage

We'll show three examples, "create", "edit" and "clone". Let's see how useModalForm is used in all.

localhost:3000/posts
import { HttpError, useTable } from "@refinedev/core";
import { useModalForm } from "@refinedev/react-hook-form";

import { Modal } from "@components";

const PostList = () => {
const { tableQueryResult } = useTable<IPost>({
sorters: {
initial: [
{
field: "id",
order: "desc",
},
],
},
});

const {
formState: { errors },
refineCore: { onFinish, formLoading },
modal: { visible, close, show },
register,
handleSubmit,
saveButtonProps,
} = useModalForm<IPost, HttpError, IPost>({
refineCoreProps: { action: "create" },
});

const loading = tableQueryResult?.isLoading;

if (loading) {
return <div>Loading...</div>;
}

return (
<div>
<Modal isOpen={visible} onClose={close}>
<form className="form" onSubmit={handleSubmit(onFinish)}>
<div className="form-group">
<label>Title: </label>
<input
{...register("title", {
required: "This field is required",
})}
/>
{errors.title && <span>{errors.title.message}</span>}
</div>
<div className="form-group">
<label>Status: </label>
<select {...register("status")}>
<option value="published">published</option>
<option value="draft">draft</option>
<option value="rejected">rejected</option>
</select>
</div>
<button type="submit" {...saveButtonProps}>
{formLoading ? "Loading" : "Save"}
</button>
</form>
</Modal>
<button onClick={() => show()}>Create Post</button>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{tableQueryResult.data?.data.map((post) => (
<tr key={post.id}>
<td>{post.id}</td>
<td>{post.title}</td>
<td>{post.status}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};

export interface IPost {
id: number;
title: string;
status: "published" | "draft" | "rejected";
}
See Modal component
src/components/Modal/index.tsx
type ModalPropsType = {
isOpen: boolean;
onClose: () => void;
children: React.ReactNode;
};

const Modal: React.FC<ModalPropsType> = ({ isOpen, onClose, children }) => {
if (!isOpen) return null;
return (
<>
<div className="overlay" onClick={onClose}></div>
<div className="modal">
<div className="modal-title">
<button className="close-button" onClick={onClose}>
&times;
</button>
</div>
<div className="modal-content">{children}</div>
</div>
</>
);
};
See styles
src/styles.css
* {
box-sizing: border-box;
}

.overlay {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: rgba(0, 0, 0, 0.7);
z-index: 1000;
}

.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
z-index: 1000;
width: 500px;
overflow-y: auto;
}

.modal .modal-title {
display: flex;
justify-content: flex-end;
padding: 4px;
}

.modal .modal-content {
padding: 0px 16px 16px 16px;
}

.form {
display: flex;
flex-direction: column;
gap: 8px;
}

.form .form-group {
display: flex;
flex-direction: column;
gap: 4px;
}

.form input,
select,
textarea {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}

Properties

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

All React Hook Form useForm props also available in useModalForm. You can find descriptions on React Hook Form docs.

defaultValues

Default values for the form. Use this to pre-populate the form with data that needs to be displayed. This property is only available with "create" action.

const modalForm = useModalForm({
defaultValues: {
title: "Hello World",
},
});

defaultVisible

When true, modal will be visible by default. Defaults to false.

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

autoSubmitClose

When true, modal will be closed after successful submit. Defaults to true.

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

autoResetForm

When true, form will be reset after successful submit. Defaults to true.

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

warnWhenUnsavedChanges

When you have unsaved changes and try to leave the current page, Refine shows a confirmation modal box. To activate this feature. By default, this feature is disabled.

You can also set this value in <Refine> component.

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

syncWithLocation

When true, the modals visibility state and the id of the record will be synced with the URL. By default, this feature is disabled.

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 },
});

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.

By default the autoSave feature does not invalidate queries. However, you can use the invalidateOnUnmount and invalidateOnClose props to invalidate queries upon unmount or close.

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

autoSave feature operates exclusively in edit mode. Users can take advantage of this feature while editing data, as changes are automatically saved in editing mode. However, when creating new data, manual saving is still required.

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. By default, it is set to false.

useModalForm({
refineCoreProps: {
autoSave: {
enabled: true,
},
},
});

debounce

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

useModalForm({
refineCoreProps: {
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({
refineCoreProps: {
autoSave: {
enabled: true,
onFinish: (values) => {
return {
foo: "bar",
...values,
};
},
},
},
});

invalidateOnUnmount

This prop is useful when you want to invalidate the list, many and detail queries from the current resource when the hook is unmounted. By default, it invalidates the list, many and detail queries associated with the current resource. Also, You can use the invalidates prop to select which queries to invalidate. By default it is set to false.

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

invalidateOnClose

This prop is useful when you want to invalidate the list, many and detail queries from the current resource when the modal is closed. By default, it invalidates the list, many and detail queries associated with the current resource. Also, You can use the invalidates prop to select which queries to invalidate. By default it is set to false.

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

Return Values

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

All React Hook Form useForm return values also available in useModalForm. You can find descriptions on useForm 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,
handleSubmit,
register,
modal,
refineCore: { onFinish },
} = useModalForm();

return (
<>
<button onClick={show}>Show Modal</button>
<Modal {...modal}>
<form onSubmit={handleSubmit(onFinish)}>
<div>
<label>Title: </label>
<input {...register("title")} />
</div>
<div>
<button type="submit" onClick={modal.close}>
Cancel
</button>
<button type="submit" onClick={modal.submit}>
Save
</button>
</div>
</form>
</Modal>
</>
);

submit

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

const {
getInputProps,
handleSubmit,
register,
modal,
refineCore: { onFinish },
} = useModalForm();

// ---

return (
<>
<button onClick={show}>Show Modal</button>
<Modal {...modal}>
<form onSubmit={handleSubmit(onFinish)}>
<div>
<label>Title: </label>
<input {...register("title")} />
</div>
<div>
<button type="submit" onClick={modal.submit}>
Save
</button>
</div>
</form>
</Modal>
</>
);

show

A function that can show the modal.

const {
saveButtonProps,
handleSubmit,
register,
modal,
refineCore: { onFinish, formLoading },
} = useModalForm();

return (
<>
<button onClick={show}>Show Modal</button>
<Modal {...modal}>
<form onSubmit={handleSubmit(onFinish)}>
<div>
<label>Title: </label>
<input {...register("title")} />
</div>
<div>
<button type="submit" {...saveButtonProps}>
Save
</button>
</div>
</form>
</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 {
saveButtonProps,
handleSubmit,
register,
modal,
refineCore: { onFinish, formLoading },
} = useModalForm();

return (
<>
<button onClick={show}>Show Modal</button>
<Modal {...modal}>
<form onSubmit={handleSubmit(onFinish)}>
<div>
<label>Title: </label>
<input {...register("title")} />
</div>
<div>
<button
type="submit"
disabled={saveButtonProps.disabled}
onClick={(e) => {
// -- your custom logic
saveButtonProps.onClick(e);
}}
>
Save
</button>
</div>
</form>
</Modal>
</>
);

API Reference

Properties

PropertyTypeDescriptionDefault
refineCoreProps

Configuration object for the core of the useForm

warnWhenUnsavedChanges

boolean

When you have unsaved changes and try to leave the current page, refine shows a confirmation modal box.

false*

disableServerSideValidation

boolean

Disables server-side validation

false

modalProps

{ defaultVisible?: boolean; autoSubmitClose?: boolean; autoResetForm?: boolean; }

Configuration object for the modal. defaultVisible: Initial visibility state of the modal.

autoSubmitClose: Whether the form should be submitted when the modal is closed.

autoResetForm: Whether the form should be reset when the form is submitted.

defaultVisible = false autoSubmitClose = true autoResetForm = true

syncWithLocation

boolean

{ key?: string; syncId?: boolean; }

undefined

If true, the form will be synced with the location. If an object is passed, the key property will be used as the key for the query params. By default, query params are placed under the key, ${resource.name}-${action}.

External Props:

It also accepts all props of useForm hook available in the React Hook Form.

Type Parameters

PropertyDescriptionTypeDefault
TQueryFnDataResult data returned by the query function. Extends BaseRecordBaseRecordBaseRecord
TErrorCustom error object that extends HttpErrorHttpErrorHttpError
TVariablesField Values for mutation function{}{}
TContextSecond generic type of the useForm of the React Hook Form.{}{}
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 modalModalReturnValues
refineCoreThe return values of the useForm in the coreUseFormReturnValues
React Hook Form Return ValuesSee React Hook Form 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.BaseSyntheticEvent) => void; }

Example

Run on your local
npm create refine-app@latest -- --example form-react-hook-form-use-modal-form