
ReactUIライブラリMantineのフォームAPIを使用する
この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
こんにちは。データアナリティクス事業本部 サービスソリューション部の北川です。 今回は、MantineのフォームAPIを触っていこうと思います。
Mantineとは、ReactのUIライブラリの一つです。UIコンポーネントの他にも、フォームの状態を管理する機能を提供します。
詳しくは、こちらの記事で紹介しています。 https://dev.classmethod.jp/articles/mantine-hooks/
Mantine Formを使用
早速Mantine Formのuse-formを使用します。
Next.jsのプロジェクト立ち上げ
npx create-next-app --ts
Mantineをインストール
yarn add @mantine/hooks @mantine/form @mantine/core @mantine/next
//または
npm install @mantine/hooks @mantine/form @mantine/core @mantine/next
index.tsxの変更
import { TextInput, Checkbox, Button, Group, Box } from "@mantine/core";
import { useForm } from "@mantine/form";
type Form = {
username: string;
email: string;
termsOfService: boolean;
}
const Home = () => {
const form = useForm<Form>({
initialValues: {
username: "",
email: "",
termsOfService: false,
},
validate: {
username: (value) =>
value.length < 2 ? "Name must have at least 2 letters" : null,
email: (value) => (/^\S+@\S+$/.test(value) ? null : "Invalid email"),
},
});
return (
<Box sx={{ maxWidth: 300 , margin: 100}} mx="auto">
<form onSubmit={form.onSubmit((values) => console.log(values))}>
<TextInput
required
label="username"
placeholder=""
{...form.getInputProps("username")}
/>
<TextInput
required
label="Email"
placeholder="your@email.com"
{...form.getInputProps("email")}
/>
<Checkbox
mt="md"
label="I agree to sell my privacy"
{...form.getInputProps("termsOfService", { type: "checkbox" })}
/>
<Group position="right" mt="md">
<Button type="submit">Submit</Button>
</Group>
</form>
</Box>
);
}
export default Home;
useFormに初期値や、バリデーションを記述します。状態は、form.valueに保持します。チェックボックスの状態なども管理できます。
便利なプロパティ
Mantine Formには便利なプロパティが多くあります。
setValues
form.setValuesで値を変更できます。
<Button onClick={() => form.setValues({...form.values, username: "testUser”})}>変更</Button>
// フォームの値を(ユーザー名を”testUser”に)変更
setFieldValue
また、今回のように変更するキーが一つなら、setFieldValue()も使えます。第一引数に変更したいキー、第二引数に変更値を指定して記述します。
<Button onClick={() => form.setFieldValue("username", "testUser2")}>変更2</Button>
// usernameをtestUser2に変更
reset
状態を初期値に戻します。フォームを送信した後によく使いますね。
const func = (value: Form) => {
// フォームの状態を処理する記述
form.reset();
//処理が完了した後にフォームの値をリセットさせる
}
error
エラー文を表示させます。
<Button onClick={() => form.setErrors({ username: 'Invalid name', email: 'Invalid email' })}>エラー表示</Button>
validate
form.validateを使用することで、任意のタイミングでバリデーションを実行することができます。
<Button onClick={() => form.validate()}>バリデーション実行</Button>
まとめ
フォームライブラリの中でも人気のあるreact-hook-formと比較しても、使用感に大きな違いはありませんでした。 バリデーションの記述に癖もなく、react-hook-formを使っていた方なら使いやすいと思います。Mantineのフォーム用コンポーネントを使用するなら、Mantine Formを使うのは必須ですね笑。
また、use-form以外にも、use-form listsを使用すれば、指定したプロパティを持つフォームの数を、コントロールすることができます。Mantineは公式ドキュメントも丁寧で、わかりやすいので、気になる方はドキュメントも覗いてみてください。
ではまた