概要
Redux Form 公式のサンプルはBootstrapベースなので、「Field-level Validation Example」のサンプルを Semantic UI React で書き換えたというもの。
Redux Formはバリデーションフォームを作る際によく用いられ、他方 Semantic UI React もパーツが充実してきて最近のお気に入りなので、テンプレートおよび備忘録的に残しておく意図で書いたもの。
リファレンス
出来上がったもの
- ソースコード - @yamaryu0508/redux-form-semantic-ui
- 公開ページ - https://yamaryu0508.github.io/redux-form-semantic-ui/
ポイント
ValidationForm.jsx
- Semantic UI Reactの
Form
等のコンポーネントと Redux Form のField
コンポーネントを組合せて利用する部分。Bootstrapでform
だった部分をForm
に変えるだけではあるが、Semantic UI Reactを適用するためのポイントと言える -
Field
中のcomponent
部分の定義。componet
を Semantic UI React のコンポーネントで定義し直す部分。これもinput
を Semantic UI React のForm.Input
等に置き換えていくだけではあるが、やはり Semantic UI React を適用するためのポイント
ValidationForm.jsx
import React from "react";
import { Field, reduxForm } from "redux-form";
import { Button, Form } from "semantic-ui-react";
import { renderText } from "./SemanticFields";
import {
required,
maxLength15,
email,
aol,
number,
minValue13,
tooYoung
} from "./Validations";
const ValidationForm = props => {
const { handleSubmit, pristine, reset, submitting } = props;
return (
<Form>
<Field
required
name="username"
type="text"
component={renderText}
label="Username"
validate={[required, maxLength15]}
/>
<Field
name="email"
type="email"
component={renderText}
label="Email"
validate={email}
warn={aol}
/>
<Field
required
name="age"
type="number"
component={renderText}
label="Age"
validate={[required, number, minValue13]}
warn={tooYoung}
/>
<Form.Group>
<Button
color="blue"
icon="checkmark"
labelPosition="right"
content="Submit"
onClick={handleSubmit}
disabled={submitting}
/>
<Button
content="Clear Values"
onClick={reset}
disabled={pristine || submitting}
/>
</Form.Group>
</Form>
);
};
export default reduxForm({
form: "form"
})(ValidationForm);
SemanticFields.jsx
-
Field
中のcomponent
部分は Semantic UI React のForm.Input
等に置き換えると良いが、メッセージ表示を行おうとすると、レイアウト等をどうするか一考必要で、今回はForm.Field
で括ることで解決を図った
SemanticFields.jsx
import React from "react";
import { Form } from "semantic-ui-react";
export const renderText = ({
input,
type,
label,
placeholder,
meta: { touched, error, warning },
...props
}) => (
<Form.Field>
<Form.Input
{...input}
{...props}
error={touched && error && true}
label={label}
placeholder={placeholder}
/>
<Form.Field>
{touched &&
((error && <i style={{ color: "#9f3a38" }}>{error}</i>) ||
(warning && <i style={{ color: "#9f3a38" }}>{warning}</i>))}
</Form.Field>
</Form.Field>
);