A
A
Anastasia2022-03-28 11:38:51
React
Anastasia, 2022-03-28 11:38:51

How to properly setup react-hook-form and Select from React-select to work?

When connecting react-hook-form rules for validation do not work

import React, { useState } from 'react';
import { CustomSelect as Select } from '../Select/Select';
import { useForm, Controller } from 'react-hook-form';
import { Button } from '../Button/Button';

type TSelect = {
  value: string;
  label: string;
  name: string;
};

interface ISelectProps {
  options?: TSelect[];
}

export const DefaultSelect = ({ options = [] }: ISelectProps) => {
  const {
    handleSubmit,
    control,
    formState: { errors, isValid, touchedFields },
  } = useForm({ mode: 'onChange', criteriaMode: 'firstError' });
  const onSubmit = (data: any) => {
    console.log(data);
  };

  return (
    <>
      <Controller
        name='brand'
        control={control}
        render={({
          field: { onChange, onBlur, value, name, ref },
          fieldState: { invalid, isTouched, isDirty, error },
          formState,
        }) => {
          return (
            <Select
              caption='Марка авто'
              placeholder='Выберите марку'
              options={options}
              wrapClassName='filter_select_wrapper'
              value={value}
              onChange={onChange}
              onBlur={onBlur}
              refs={{ ref, name }}
            />
          );
        }}
        rules={{
          validate: {
            required: value => value.trim().length > 0 || 'Input is required',
          },
          maxLength: {
            value: 5,
            message: 'Input cannot be more than 5 characters.',
          },
          pattern: {
            value: /^[^/\\:*?<>]+$/,
            message: 'Input cannot have the following characters: / \\ : * ? < >',
          },
        }}
      />
      <Button onClick={handleSubmit(onSubmit)}>Отправить</Button>
    </>
  );
};


import React from 'react';
import CreatableSelect from 'react-select/creatable';
import { components } from 'react-select';
import clsx from 'clsx';
import { Typography } from '../Typography/Typography';
import { ISelectProps } from './types';
import { selectStyles } from './style';
import stylesTypography from '../Typography/Typography.module.scss';
import styles from './SelectCreatable.module.scss';

export const SelectCreatable = ({
  options = [],
  placeholder = 'Выберите',
  caption,
  errorText,
  wrapClassName,
  labelClassName,
  className,
  size = '100%',
  prefix,
  disabled = false,
  isLoading,
  refs,
  inputProps,
  ...props
}: ISelectProps) => {
  const customStyles = selectStyles(errorText, size, options, prefix);

  const Input = (initialProps: any) => {
    const customInput = <components.Input {...initialProps} />;
    return prefix ? (
      <div className={styles.Control}>
        <Typography textStyle='textM' className={stylesTypography.Typography_text_secondary}>
          {prefix}
        </Typography>
        <div className={styles.Control_option}>{customInput}</div>
      </div>
    ) : (
      customInput
    );
  };

  return (
    <div className={clsx(wrapClassName)}>
      <label className={labelClassName}>
        {caption && (
          <Typography textStyle='textS' className={styles.Select_label}>
            {caption}
          </Typography>
        )}
      </label>
      <div className={clsx(styles.Select_wrapper, disabled && styles.Select_wrapper_disabled)}>
        <CreatableSelect
          options={options}
          styles={customStyles}
          placeholder={placeholder}
          formatCreateLabel={() => null}
          loadingMessage={() => 'Загрузка данных'}
          isLoading={isLoading}
          isDisabled={disabled}
          components={{ Input }}
          {...refs}
          {...props}
        />
      </div>
      {errorText && (
        <Typography textStyle='menuItem' className={styles.Select_error}>
          {errorText}
        </Typography>
      )}
    </div>
  );
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wonderingpeanut, 2022-03-28
@wonderingpeanut

Hello.
In your code, validate.required will always be true.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question