A react-hook for managing form values, errors and more
A react-hook for managing form values, errors and more
Preparations
The form-shape and how it should be validated is defined using the useFormstate function.
Optimally this should be outside of your react-component.
``typescript jsx
type FormData = { // Don't use an interface here. Read me under "known issues"
name: string;
city: string;
hobby: string;
}
interface FormProps {
validate: boolean;
}
const initialState: FormData = {
name: '',
city: '',
hobby: ''
};
const validator = useFormstate
name: (value) => value.length > 256 ? 'Thats a might long name' : undefined,
city: (value, values, props) => {
if (props.validate) {
return value.length === 0 ? 'Must provide a city' : undefined
}
return undefined;
},
hobby: (value, values, props) => {
if (values.city.length > 0 && props.validate) {
return value.length === 0 ? 'Hobby is required if city is provided' : undefined
}
return undefined;
}
});
`
As an alternative you may pass a function instead of an object to useFormstate.`
This may useful in instances where form-elements are conditonally-validated, though the two approaches are functionally equivalent.typescript jsx
const validator = useFormstate
const name = values.name.length > 256 ? 'Thats a might long name' : undefined;
const city = props.validate && values.city.length === 0 ? 'Must provide a city' : undefined;
const hobby = values.city.length > 0 && props.validate && values.hobby.length === 0 ? 'Hobby is required if city is provided' : undefined;
return { name, city, hobby };
});
`
Use it
`typescript jsx
function submithandler(values: FormData) {
return fetch('...Do your thing...');
}
function MyForm(props: Props) {
const state: Formstate
return (
{state.field.city.error ? state.field.city.error : undefined}
{state.field.hobby.error ? state.field.hobby.error : undefined}
);
}
`
and FieldState:Formstate
The returntype of calling
useFormstate(validation)(initialValues, props);
`
submitting: boolean; // is the submithandler current running
pristine: boolean; // is 'values === initialValues'
valid: boolean; // is the form as a whole valid, e.g no errors
errors: { fieldnames: string };
fields: { fieldnames: FieldState }
`FieldState
The type containing information for each field.
`
pristine: boolean; // is 'values === initialValues'
touched: boolean; // has this element had focus
initialValue: boolean; // initialValue as specified
error?: string; // this elements error if any
input: {
id: string;
name: string;
value: string;
onChange: ChangeEventHandler;
onBlur: FocusEventHandler;
};
`Known issues
$3
Its recommended to use type insteadof interface when defining your form-shape.
E.g
`typescript
// DON'T DO THIS
interface FormShape {
name: string;
}// DO THIS
type FormShape = {
name: string;
}
``Made using the awesome typescript library starter