9worphi-useform
v1.0.0
Published
React hook for form control and validation
Downloads
4
Readme
useForm Hook
Como utilizar
import useForm from "9worphi-useForm";
const formFields = {
title: {
label: "Título",
value: "",
validation: value => value !== "Teste" && value !== "",
errorFeedback: "Insert a title"
},
content: {
label: "content",
value: ""
},
author: {
label: "Author",
type: "text",
value: "",
validation: value => value !== ""
}
};
const FormQualquer = () => {
// Chamando o Hook
const [formState, setField, validate] = useForm(formFields);
// formState = Estado atual do form, com valores e validações
// setField = função para alterar campos do formulário
// validate = função para validar os campos conforme as "validations" acima
const onSubmit = e => {
e.preventDefault();
validate(({ errors, fields }) => {
if (Object.values(errors).length > 0) {
return;
}
console.log(fields);
});
};
return (
<form onSubmit={onSubmit}>
{/* Aplica um .map no formState para montar os campos */}
{Object.keys(formState).map(key => {
const field = formState[key];
const label = <label htmlFor={key}>{field.label}</label>;
const errorFeedback = field.errorFeedback && (
<div className="invalid-feedback">{field.errorFeedback}</div>
);
return (
<div key={key}>
{label}
<br />
<input
type="text"
invalid={field.invalid}
value={field.value}
// setField(campo, { propriedade: valor })
onChange={e => setField(key, { value: e.target.value })}
/>
{errorFeedback}
</div>
);
})}
<button type="submit">OK</button>
</form>
);
};