From 4bea6cd3d67d9e5942d08f0c902dcd4844c6f999 Mon Sep 17 00:00:00 2001 From: Alberto Defendi <1369-ahl-berto@users.noreply.gitlab.inf.unibz.it> Date: Thu, 29 Apr 2021 15:06:14 +0200 Subject: [PATCH] Move to root for component reusing --- .../AuthUser/InputField/InputField.md | 24 ++++++++ .../AuthUser/InputField/InputField.tsx | 60 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 src/components/AuthUser/InputField/InputField.md create mode 100644 src/components/AuthUser/InputField/InputField.tsx diff --git a/src/components/AuthUser/InputField/InputField.md b/src/components/AuthUser/InputField/InputField.md new file mode 100644 index 0000000..895642c --- /dev/null +++ b/src/components/AuthUser/InputField/InputField.md @@ -0,0 +1,24 @@ +Wrapper for any input field + +```js +import { SubmitHandler, useForm } from 'react-hook-form'; +const { control } = useForm(); + +<InputField + name="password" + control={control} + rules={{ + minLength: 8, + maxLength: 60, + required: { + value: true, + message: 'Insert valid password', + }, + }} + label="Password" + error={false} + errorMessage="Insert valid password" +/> + + +``` diff --git a/src/components/AuthUser/InputField/InputField.tsx b/src/components/AuthUser/InputField/InputField.tsx new file mode 100644 index 0000000..ee002a4 --- /dev/null +++ b/src/components/AuthUser/InputField/InputField.tsx @@ -0,0 +1,60 @@ +import React, { FC } from 'react'; +import { TextField } from '@material-ui/core'; +import { Control, Controller, FieldValues } from 'react-hook-form'; + +type Props = { + /** + * Name of the elemement. (ex. email, password). + */ + name: string; + /** + * Aria label. + */ + label: string; + /** + * Takes error from react-hook-form and is thrown if + * the component is not valid. + */ + error: boolean; + /** + * Message to display if the component is not valid. + */ + errorMessage: string; + /** + * React-hook-form control. + */ + control: Control<FieldValues> | undefined; + /** + * Validation rules. + */ + rules: Partial<unknown>; +}; + +export const InputField: FC<Props> = (props: Props) => { + const { name, label, error, errorMessage, control, rules } = props; + return ( + <Controller + name={name} + control={control} + rules={rules} + render={({ onChange, value }) => ( + <TextField + variant="outlined" + margin="normal" + type={name} + required + fullWidth + id={name} + label={label} + name={name} + onChange={onChange} + value={value} + autoComplete={name} + autoFocus + error={error} + helperText={error && errorMessage} + /> + )} + /> + ); +}; -- GitLab