Skip to content
Snippets Groups Projects
InputField.tsx 1.34 KiB
Newer Older
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}
        />
      )}
    />
  );
};

InputField.defaultProps = {
  rules: undefined,
};