react-use-form-lite
Version:
Hook de formularios para React moderno: rápido, ligero, sin dependencias y compatible con TypeScript. Soporta inputs, selects, checkboxes, radios y archivos con validación simple.
103 lines (102 loc) • 3.21 kB
JavaScript
// src/index.ts
import { useState } from "react";
function useFormLite(initialValues, onSubmitCallback) {
const [values, setValues] = useState(initialValues);
const handleChange = (event) => {
const target = event.target;
const name = target.name;
let processedValue;
if (target instanceof HTMLInputElement) {
if (target.type === "checkbox") {
if (Array.isArray(values[name])) {
const arr = Array.isArray(values[name]) ? [...values[name]] : [];
if (target.checked) {
if (!arr.includes(target.value)) arr.push(target.value);
} else {
const idx = arr.indexOf(target.value);
if (idx > -1) arr.splice(idx, 1);
}
processedValue = arr;
} else {
processedValue = target.checked;
}
} else if (target.type === "number") {
processedValue = target.value === "" ? "" : !isNaN(target.valueAsNumber) ? target.valueAsNumber : target.value;
} else if (target.type === "date") {
processedValue = target.value ? /* @__PURE__ */ new Date(`${target.value}T00:00:00`) : null;
} else if (target.type === "file") {
if (target.multiple) {
processedValue = target.files ? Array.from(target.files) : [];
} else {
processedValue = target.files && target.files[0] ? target.files[0] : null;
}
} else {
processedValue = target.value;
}
} else {
processedValue = target.value;
}
setValues((prevValues) => ({
...prevValues,
[name]: processedValue
}));
};
const handleSubmit = (event) => {
event.preventDefault();
onSubmitCallback(values);
};
const resetForm = () => {
setValues({ ...initialValues });
};
const register = (fieldName) => {
let currentValue = values[fieldName] ?? initialValues[fieldName] ?? "";
if (currentValue === void 0) {
currentValue = initialValues[fieldName];
}
let displayValue;
if (isValidDate(currentValue)) {
const year = currentValue.getFullYear();
const month = (currentValue.getMonth() + 1).toString().padStart(2, "0");
const day = currentValue.getDate().toString().padStart(2, "0");
displayValue = `${year}-${month}-${day}`;
} else if (currentValue === null || currentValue === void 0) {
displayValue = "";
} else {
displayValue = currentValue;
}
return {
name: fieldName,
value: displayValue,
onChange: handleChange
};
};
const registerFile = (fieldName) => {
return {
name: fieldName,
onChange: handleChange
};
};
const getEmptyFields = () => {
const emptyFields = {};
for (const key in values) {
if (values[key] === "" || values[key] === null || values[key] === void 0 || Array.isArray(values[key]) && values[key].length === 0) {
emptyFields[key] = "Este campo est\xE1 vac\xEDo";
}
}
return emptyFields;
};
return {
values,
handleSubmit,
resetForm,
register,
registerFile,
getEmptyFields
};
}
function isValidDate(value) {
return value instanceof Date && !isNaN(value.getTime());
}
export {
useFormLite
};