How to make react-select required in a form?
I need to make react-select required in a form,
Required in prop types of your component form ?
@cnamazone I guess you can import Select from react-select inside your form container component then pass Select as props.
Then, check the prop type.
But why can't you directly import Select in your form ?
i have the same issue, i need to make my react-select to be required, ex: birth date with year, month ,day dropdown
This might be a dupe of https://github.com/JedWatson/react-select/issues/1453
for security reasons if you cannot validate data then you risk your applications being compromised.
This is on the roadmap for our team in the upcoming set of releases. It's a non-trivial body of work, so we're taking our time to make sure we get it right. Thanks for your patience and understanding everyone. 🙏
Any update here?
+1
Any updates?
Is this repo still getting maintained ? Just curious, should I make PR ?
@Rutulpatel7077 @gwyneplaine Managed to do this with custom input component and just passed a flag into props, then got it from props.selectProps.selectProps. It does not seem to support this but it's flexible enough to do kinda everything you want. My app is in clojurescript (bit of interop with js) don't know how helpful a code example would be.
I think the simplest solution is to add another hidden input now. I have added simple input under react-select field.
<Fragment>
<Select {...rest} options={options} filterOptions={filterOptions} />
{!props.disabled && (
<input
tabIndex={-1}
autoComplete="off"
style={{ opacity: 0, height: 0 }}
value={value}
required={required}
/>
)}
</Fragment>

https://codesandbox.io/s/react-select-v2-required-input-3xvvb?fontsize=14
In some cases you do need position absolute in style
Hey, so I got this asterisk to appear as desired, looks exactly like the built in one. This is for fully managed fields, so there's no form tag, I disable the form myself with JS. This is the big problem I had, and searching led me here.
I make a wrapper component and give the Select a className like "my-className" in the props, and I append " required" to the className based on a required prop. That's not classNamePrefix
Then apply this css
.my-className.required::after {
content: "*";
color: rgb(255, 95, 95);
position: absolute;
top: -5px;
right: -10px;
}
Like this:

Any update on this?
Any ETA on this?
Hi, i used ref to make the input field required on componentDidMount, you can try the same.
On Wed, 29 Jul 2020, 20:25 Giancarlo Brusca, [email protected] wrote:
Any ETA on this?
— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/JedWatson/react-select/issues/3140#issuecomment-665713970, or unsubscribe https://github.com/notifications/unsubscribe-auth/AFKDT4CTDO3FNHEN2KACILDR6AZ6VANCNFSM4F647WEA .
Hi, i used ref to make the input field required on componentDidMount, you can try the same. … On Wed, 29 Jul 2020, 20:25 Giancarlo Brusca, @.***> wrote: Any ETA on this? — You are receiving this because you commented. Reply to this email directly, view it on GitHub <#3140 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/AFKDT4CTDO3FNHEN2KACILDR6AZ6VANCNFSM4F647WEA .
this.topicRef.current.select.inputRef.required = true;
I'm using the version 3.1.0. I couldn't access to the input ref. I created a simple Select wrapper.
import React from 'react'
import Select from 'react-select';
const SelectWrap = props => {
const { value, required, disabled, className } = props;
let pardeValue = value;
if(Array.isArray(value) || typeof value === 'object')
pardeValue = Object.keys(value).length > 0 ? value : "";
return (
<div className="select-wrapper-container">
<Select {...props} className={`${className} select-wrapper`}/>
<input
className="input-required"
type="text"
value={pardeValue && JSON.stringify(pardeValue)}
tabIndex={-1}
autoComplete="off"
required={required}
disabled={disabled}
/>
</div>
)
}
export default SelectWrap
The style can be more simple, but I want to make my hidden input the same size of the select.
.select-wrapper-container{
position: relative;
.select-wrapper{
position: relative;
z-index: 1;
}
.input-required{
position: absolute;
border: 0;
color: transparent;
background-color: transparent;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 0;
}
}
The best way I found is to create a transparent input field that will be queried via javascript standard checkValidity. This should have absolute positioning and 100% width & height. You can then bind a listener to the input field for the invalid event created by checkValidity
Here is the code I use. There are alterations for use of value field as well as some styling (for MDB inputs) , but you can just change the classes of input to match your own styles libraries. In this manner your validation styling will be the same as your existing form inputs.
Hopes this helps someone.
/**************************************************************************************
*** Select - New Select Control Using react-select (to stop stupid probs with MDB) ***
**************************************************************************************/
// Use This progressively instead of InputSelect
/* Differences from native ReactSelect
Validation - Applies transparent input overlay that works with form checkValidity()
value: This is the record.field value not an object {label: x, value: y} as for react-select
grouped: Explicitly set grouped options when set true
objValue: Works the same as react-select value object
*/
// Note: value property works differently do react-select , use ObjValue to work same as react-select
export const Select = (props) => {
let { id, options, cols, value, objValue, label, grouped, ...o } = props
id = id ? id : 'react-select'
const [selected, setSelected] = useState(value)
const [invalid, setInvalid] = useState(false)
//DEFAULTS
if (!grouped) grouped = false
//--------------------------
// VALIDATION EVENT HANDLERS
//--------------------------
useEffect(() => {
//ADD EVENT HANDLER FOR FOR VALIDATION
let ele = document.getElementById(`${id}_invalid}`)
ele.addEventListener('invalid', (e) => {
console.log('e is ', selected, e)
if (typeof selected === 'undefined' || selected !== null) setInvalid(true)
})
//ON COMPONENT EXIT - REMOVE EVENT HANDLER
return () => {
ele.removeEventListener('invalid', () => {
setInvalid(false)
})
}
// eslint-disable-next-line
}, [])
//Value property (Allows Single field assignent) - translates to object in for {label:x, value:y}
useEffect(() => {
let val
if (grouped) {
val = _.findInGroup(options, 'options', (rec) => rec.value === value)
} else {
val = options.find((rec) => rec.value === value)
}
//console.log('Selected==>', val)
setSelected(val)
// eslint-disable-next-line
}, [value, options])
//objValue Property (Emulate standard react-select value object)
useEffect(() => {
if (objValue) {
setSelected(objValue)
}
// eslint-disable-next-line
}, [objValue])
//STYLING SAME AS MDB INPUT COMPONENTS
const customStyles = {
valueContainer: (provided, state) => ({
...provided,
backgroundColor: 'aliceblue',
}),
dropdownIndicator: (provided, state) => ({
...provided,
backgroundColor: 'aliceblue',
}),
}
const handleChange = (opt, i) => {
setSelected(opt)
//Callback function (i is used for nested data in record)
if (props && props.onChange) props.onChange(opt, i)
}
return (
<Col cols={cols}>
{label && <label className='tp-label text-uppercase'>{label}</label>}
<div className='select-wrapper'>
<ReactSelect
styles={customStyles}
value={selected ? selected : ''}
options={options}
onChange={(val, i) => handleChange(val, i)}
isSearchable={true}
{...o}
/>
<input
id={`${id}_invalid}`}
name={`${id}_invalid}`}
value={selected ? selected : ''}
onChange={() => {}}
tabIndex={-1}
className={`form-control tp-input w-100 ${invalid ? '' : 'd-none'}`}
autoComplete='off'
//value={selected}
onFocus={() => {
setInvalid(false)
}}
style={{
position: 'absolute',
color: 'transparent',
backgroundColor: 'transparent',
top: 0,
left: 0,
width: '100%',
height: '100%',
zIndex: 0,
}}
required={true}
/>
</div>
</Col>
)
}
serously, this has been open for 2 years? 😮