I need a simple "required" validation for 'react-select' (github repo). In the latest version it uses css-in-js approach. So I have custom styles:
export const customStyles = {
 control: (base, state) => ({
        ...base,
    }),
    menu: (base, state) => ({
        ...base,
    }),
    menuList: (base, state) => ({
        ...base,
    }),
}
How can I change e.g. borderColor if field is invalid?
On this point there's an issue opened on GitHub.
I see two different approaches:
className. Example here.customSelect in a separate file. Then you can pass a props isValid and use it to change your borderColor.class CustomSelect extends React.Component {
  render() {
    const {
      isValid
    } = this.props
    
    const customStyles = {
      control: (base, state) => ({
        ...base,
        // state.isFocused can display different borderColor if you need it
        borderColor: state.isFocused ?
          '#ddd' : isValid ?
          '#ddd' : 'red',
        // overwrittes hover style
        '&:hover': {
          borderColor: state.isFocused ?
            '#ddd' : isValid ?
            '#ddd' : 'red'
        }
      })
    }
    return <Select styles={ customStyles } {...this.props}/>
  }
}
A help for someone who doesn't want to add all time some codes for only of this required validation in react-select. Just use react-hook-form-input.
<RHFInput
   as={<Select options={options} />}
   rules={{ required: 'Please select an option'}}
   name="reactSelect"
   register={register}
   setValue={setValue}
/>
Where this RHFInput from react-hook-form-input was just a save for me.. Complete example- react-hook-form-input.
import React from 'react';
import useForm from 'react-hook-form';
import { RHFInput } from 'react-hook-form-input';
import Select from 'react-select';
const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
];
function App() {
  const { handleSubmit, register, setValue, reset, errors } = useForm();
  return (
    <form onSubmit={handleSubmit(data => console.log(data))}>
      <RHFInput
        as={<Select options={options} />}
        rules={{ required: 'Please select an option'}}
        name="reactSelect"
        register={register}
        setValue={setValue}
      />
      <span className="text-danger">
        {errors.reactSelect && errors.reactSelect.type === 'required' && "Please select"}
      </span>
      <button type="button">Reset Form</button>
      <button>submit</button>
    </form>
  );
}
Hope, it will help someone like me as a beginner in react.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With