78 lines
2.2 KiB
JavaScript
78 lines
2.2 KiB
JavaScript
import React, { useState, useEffect } from 'react';
|
|
import { Formik, Field, Form, ErrorMessage } from 'formik';
|
|
|
|
export function UserFormFormik({ onSubmit, errors }) {
|
|
const [ initialValues, setInitialValues ] = useState({
|
|
username: '',
|
|
password: '',
|
|
passwordVerification: ''
|
|
});
|
|
|
|
useEffect(() => {
|
|
// Reset values on errors
|
|
setInitialValues(initialValues => ({ ...initialValues }));
|
|
}, [errors]);
|
|
|
|
|
|
return (
|
|
<Formik
|
|
initialValues={initialValues}
|
|
enableReinitialize={true}
|
|
initialErrors={errors}
|
|
onSubmit={(values, setSubmitting) => {
|
|
onSubmit(values);
|
|
setSubmitting(false);
|
|
}}
|
|
validate={(values) => {
|
|
const errors = {};
|
|
|
|
if (!values.username) {
|
|
errors.username = 'Le nom d\'utilisateur ne peut être vide !';
|
|
};
|
|
|
|
if (!values.password) {
|
|
errors.password = 'Le mot de passe ne peut pas être vide !';
|
|
}
|
|
|
|
if (values.password !== values.passwordVerification) {
|
|
errors.passwordVerification = 'Vos deux mots de passe sont différents !';
|
|
}
|
|
|
|
return errors;
|
|
}}
|
|
>
|
|
{(formikProps) => (
|
|
<Form>
|
|
<BulmaField name="username" label="Nom d'utilisateur" />
|
|
<BulmaField type="password" name="password" label="Mot de passe" />
|
|
<BulmaField type="password" name="passwordVerification" label="Mot de passe (vérification)" />
|
|
<button type="submit" className="button">Submit</button>
|
|
</Form>
|
|
)}
|
|
</Formik>
|
|
);
|
|
}
|
|
|
|
export function BulmaField({ name, label }) {
|
|
return (
|
|
<div className="field">
|
|
<label className="label" htmlFor={name}>{label}</label>
|
|
<div className="control">
|
|
<Field component={BulmaInput} name={name} />
|
|
</div>
|
|
<ErrorMessage component="p" className="help is-danger" name={name} />
|
|
</div>
|
|
)
|
|
}
|
|
|
|
export function BulmaInput({ type, field, form, ...props }) {
|
|
const classes = ['input'];
|
|
if (form.errors[field.name]) classes.push('is-danger');
|
|
if (form.touched[field.name] && !form.errors[field.name]) classes.push('is-success');
|
|
return (
|
|
<input
|
|
className={classes.join(' ')}
|
|
type={type ? type : 'text'}
|
|
{...field} {...props} />
|
|
)
|
|
} |