simple-mui-redux-form
v1.1.1
Published
``` npm install simple-mui-redux-form ```
Downloads
34
Readme
Установка:
npm install simple-mui-redux-form
TextInput - компонент-обертка над mui TextField
По сравнению с TextField имеет 3 дополнительных свойства, и еще 3 свойства получает от компонента высшего порядка WithErrorHandling (см. ниже)
import { TextFieldProps } from "@mui/material"
type TextInputProps = TextFieldProps & {
inputField: InputField;
needHelperText?: boolean;
onchange: (value: string, error: string) => void;
};
Производные от TextInput компоненты:
PasswordInput
type PasswordInputProps = Omit<
TextInputProps,
"InputProps" | "autoComplete" | "password"
>;
const PasswordInput: FC<PasswordInputProps & WithHandlingError> = (props) => {
const { type, handleCLick, passwordVisibility } = useTextInput(true);
return (
<TextInput
type={type}
InputProps={{
endAdornment: (
<PasswordVisibilityButton
onclick={handleCLick}
show={passwordVisibility}
/>
),
}}
{...props}
></TextInput>
);
};
и NotEmptyTextInput
const NotEmptyTextInput: FC<TextInputProps & WithHandlingError> = ({
validateHelpers = [],
...props
}) => {
return (
<TextInput
validateHelpers={[...validateHelpers, notEmpty]}
{...props}
></TextInput>
);
};
WithErrorHandling (HOC)
добавляет в TextInput свойства для обработки пользовательского ввода:
type WithErrorHandlingProps = {
validateHelpers?: Array<ValidateHelper>;
validateOptions?: ValidateOptions;
mutators?: Array<InputMutator>;
};
export type ValidateHelper = {
error_text: string;
validate: InputValidator;
};
export type InputValidator = (
inputed: string,
options: ValidateOptions
) => boolean;
export type InputMutator = (inputed: string) => string;
export type ValidateOptions = {
min?: number;
max?: number;
moreThan?: number;
lessThan?: number;
minLength?: number;
maxLength?: number;
maxAfterDot?: number;
};
Например, нужно задать минимальную длину вводимого текста 8 символов, в этом нам поможет функция-валидатор checkLength
import {checkLength, TextInput} from 'simple-mui-redux-form'
const Min8CharsInput = () => {
const validator = {validate: checkLength, error_text:'Минимум 8 символов'}
return (
<TextInput
...
validateHelpers={[validator]}
validateOptions={{minLength: 8}}
...
/>
)}
createSliceOptions
Облегчает создание слайса формы
import { createSlice } from "@reduxjs/toolkit";
import {
createSliceOptions,
isFormValid,
defaulInputField,
} from "simple-mui-redux-form";
import { RootState } from "..";
type LoginFormFieldName = "username" | "password"
const SignInSlice = createSlice(
createSliceOptions<LoginFormFieldName>("login-form", {
username: { ...defaulInputField },
password: { ...defaulInputField },
})
);
export const selectIsFormValid = (state: RootState): boolean =>
isFormValid(state.loginFormState);
export const { setInitialValues, setInputField, setTouchedAll, resetForm } =
SignInSlice.actions;
export default SignInSlice.reducer;
Что еще есть в пакете:
type InputField = {
value: string;
error: string;
unTouched: boolean;
};
type InputPayload = Omit<InputField, "unTouched">;
// N - объединение (union) имён полей формы
type FormState<N extends string> = {
[key in N]: InputField;
};
// N - объединение (union) имён полей формы
type FormPayload<N extends string> = {
[key in N]: string;
};
// N - объединение (union) имён полей формы
const useForm = <N extends string>(
inputFields: FormState<N>,
reducer: ActionCreatorWithPreparedPayload<
[N, string, string],
WithInputField<N>
>
) => {
const dispatch = useDispatch();
const formPayload = createFormPayload(inputFields);
const handleChange = (name: N) => {
return (value: string, error: string) => {
dispatch(reducer(name, value, error));
};
};
return { formPayload, handleChange };
};
// N - объединение (union) имён полей формы
type WithInputField<N> = {
inputPayload: InputPayload;
name: N;
};
const checkDiapason: InputValidator = (
inputed: string,
options: ValidateOptions
) => {
const value = Number(inputed);
if (isNaN(value)) return false;
let correct = true;
const { max, min, moreThan, lessThan } = options;
if (typeof max === "number") correct = value <= max;
if (typeof min === "number" && correct) correct = value >= min;
if (typeof moreThan === "number" && correct) correct = value > moreThan;
if (typeof lessThan === "number" && correct) correct = value < lessThan;
return correct;
};
const checkLength: InputValidator = (
inputed: string,
options: ValidateOptions
) => {
let correct = true;
const { maxLength, minLength } = options;
if (typeof minLength === "number") correct = inputed.length >= minLength;
if (typeof maxLength === "number") correct = inputed.length <= maxLength;
return correct;
};
const checkNotEmpty: InputValidator = (inputed: string) =>
checkLength(inputed, { minLength: 1 });
const notEmpty: ValidateHelper = {
validate: checkNotEmpty,
error_text: "Поле не должно быть пустым",
};
const defaulInputField: InputField = {
error: "",
value: "",
unTouched: true,
};