I want a Select
component to be required in my app
required
option is not accepted by Select
component for some reason. As well as required={true}
Error message is:
Property 'required' does not exist on type 'IntrinsicAttributes & Omit<PublicBaseSelectProps<SelectOption, false, GroupBase<SelectOption>>, StateManagedPropKeys> & Partial<...> & StateManagerAdditionalProps<...> & RefAttributes<...>
My design is
<Select
required={true}
placeholder={"Select region"}
value={props.selectedRegion}
options={props.regionsOptions}
className="width-285"
onChange={props.onSelectRegionsOptions}
/>
Why is it impossible to make a Select
component required it React? One other option I found online is to wrap the Select
in FormControl
and make the latter required, but this does not work for my validation, and also does not display required symbol and red text on the component.
This app was not made by me, I got it from another team member. There is no documentation. I just need to make one field required.
What is the solution to this problem?
2
Answers
It seems like the
Select
component doesn’t supportrequired
property as default. In this case, you can make a customSelect
component inherited the originalSelect
. I provide sample code for it.you can use the
required
property with the aboveCustomSelect
component. Hope it helps you.In short: you can’t make a
react-select
<Select>
required like you can with regular form elements.react-select
‘s<Select>
does not have arequired
prop, because it’s not a regular HTML form element (which is whererequired
would have an effect on the validation of the owning form), and such a prop would have no effect.What should happen when there is no value for a
react-select
depends entirely on your particular app, and you’ll need to do that validation "by hand". For instance, you could set thearia-invalid
prop on the field, and disable your form’s submit button.