useStepsForm
useStepsForm
allows you to manage a form with multiple steps. It provides features such as which step is currently active, the ability to go to a specific step and validation when changing steps etc.
useStepsForm
hook is extended from useForm
from the @refinedev/mantine
package. This means that you can use all the functionalities of useForm
in your useStepsForm
.
Basic Usageβ
We'll show two examples, one for creating and one for editing a post. Let's see how useStepsForm
is used in both.
- create
- edit
Here is the final result of the form: We will explain the code in following sections.
Here is the final result of the form: We will explain the code in following sections.
In this example we're going to build a Post "create"
form. To creating a multi-step form, we will use <Stepper/>
component from Mantine. To handle the state of both the form and the steps, we will use useStepsForm
hook.
To show your form inputs step by step, first import and use useStepsForm
hook in your page:
import React from "react";
import { HttpError } from "@refinedev/core";
import { Create } from "@refinedev/mantine";
type FormValues = Omit<IPost, "id">;
const PostCreatePage: React.FC = () => {
const {
saveButtonProps,
getInputProps,
values,
steps: { currentStep, gotoStep },
} = useStepsForm<IPost, HttpError, FormValues>({
initialValues: {
title: "",
status: "",
slug: "",
content: "",
},
validate: (values) => {
if (currentStep === 0) {
return {
title: values.title ? null : "Title is required",
slug: values.slug ? null : "Slug is required",
};
}
if (currentStep === 1) {
return {
status: values.status ? null : "Status is required",
};
}
return {};
},
});
return <Create>create page</Create>;
};
useStepsForm
is generic over the type form data to help you type check your code.
This hook returns a set of useful values to render <Stepper/>
. Given current value, you should have a way to render your form items conditionally with this index value.
Here, we're going to use a <Stepper/>
component to render the form items based on the currentStep
and we added <Button>
to footer with gotoStep
function to navigate between steps.
import React from "react";
import { HttpError } from "@refinedev/core";
import { Create } from "@refinedev/mantine";
type FormValues = Omit<IPost, "id">;
const PostCreatePage: React.FC = () => {
const {
saveButtonProps,
getInputProps,
values,
steps: { currentStep, gotoStep },
} = useStepsForm<IPost, HttpError, FormValues>({
initialValues: {
title: "",
status: "",
slug: "",
content: "",
},
validate: (values) => {
if (currentStep === 0) {
return {
title: values.title ? null : "Title is required",
slug: values.slug ? null : "Slug is required",
};
}
if (currentStep === 1) {
return {
status: values.status ? null : "Status is required",
};
}
return {};
},
});
return (
<Create
footerButtons={
<Group position="right" mt="xl">
{currentStep !== 0 && (
<Button
variant="default"
onClick={() => gotoStep(currentStep - 1)}
>
Back
</Button>
)}
{currentStep !== 3 && (
<Button onClick={() => gotoStep(currentStep + 1)}>
Next step
</Button>
)}
{currentStep === 2 && <SaveButton {...saveButtonProps} />}
</Group>
}
>
<Stepper
active={currentStep}
onStepClick={gotoStep}
breakpoint="xs"
>
<Stepper.Step
label="First Step"
description="Title and Slug"
allowStepSelect={currentStep > 0}
>
<TextInput
mt="md"
label="Title"
placeholder="Title"
{...getInputProps("title")}
/>
<TextInput
mt="md"
label="Slug"
placeholder="Slug"
{...getInputProps("slug")}
/>
</Stepper.Step>
<Stepper.Step
label="Second Step"
description="Status"
allowStepSelect={currentStep > 1}
>
<Select
mt="md"
label="Status"
placeholder="Pick one"
{...getInputProps("status")}
data={[
{ label: "Published", value: "published" },
{ label: "Draft", value: "draft" },
{ label: "Rejected", value: "rejected" },
]}
/>
</Stepper.Step>
<Stepper.Step
label="Final Step"
description="Content"
allowStepSelect={currentStep > 2}
>
<Textarea
label="Content"
placeholder="Content"
{...getInputProps("content")}
/>
</Stepper.Step>
<Stepper.Completed>
Completed! Form values:
<Space />
<Code mt="xl">{JSON.stringify(values, null, 2)}</Code>
</Stepper.Completed>
</Stepper>
</Create>
);
};
Propertiesβ
refineCoreProps
β
All useForm
properties also available in useStepsForm
. You can find descriptions on useForm
docs.
const stepsForm = useStepsForm({
refineCoreProps: {
action: "edit",
resource: "posts",
id: "1",
},
});
stepsProps
β
defaultStep
β
Default:
0
Sets the default starting step number. Counting starts from 0
.
const stepsForm = useStepsForm({
stepsProps: {
defaultStep: 0,
},
});
isBackValidate
β
Default:
false
When is true
, validates a form fields when the user navigates to a previous step.
const stepsForm = useStepsForm({
stepsProps: {
isBackValidate: 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 } = useStepsForm({
//...
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
.
useStepsForm({
refineCoreProps: {
autoSave: {
enabled: true,
},
}
})
debounce
β
Set the debounce time for the autoSave
prop. Default value is 1000
.
useStepsForm({
refineCoreProps: {
autoSave: {
enabled: true,
debounce: 2000,
},
}
})
Return Valuesβ
steps
β
The props needed by the <Stepper>
component.
currenStep
β
Current step, counting from 0
.
gotoStep
β
Is a function that allows you to programmatically change the current step of a form. It takes in one argument, step, which is a number representing the index of the step you want to navigate to.
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 } = useStepsForm();
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
.
import React from "react";
import { useStepsForm } from "@refinedev/mantine";
const UserCreate: React.FC = () => {
const {
saveButtonProps,
getInputProps,
values,
steps: { currentStep, gotoStep },
} = useStepsForm({
refineCoreProps: { action: "create" },
initialValues: {
name: "",
surname: "",
},
transformValues: (values) => ({
fullName: `${values.name} ${values.surname}`,
}),
});
// ...
};
API Referenceβ
Propertiesβ
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 | Form values for mutation function | {} | Record<string, unknown> |
TTransformed | Form values after transformation for mutation function | {} | TVariables |
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 valuesβ
Property | Description | Type |
---|---|---|
steps | Relevant state and method to control the steps | StepsReturnValues |
refineCore | The return values of the useForm in the core | UseFormReturnValues |
@mantine/form 's useForm return values | See useForm documentation | |
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-mantine-use-steps-form