react-select icon indicating copy to clipboard operation
react-select copied to clipboard

How to make react-select required in a form?

Open cnamazone opened this issue 8 years ago • 49 comments

I need to make react-select required in a form,

cnamazone avatar Oct 24 '18 06:10 cnamazone

Required in prop types of your component form ?

Thebarda avatar Oct 24 '18 08:10 Thebarda

@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 ?

Thebarda avatar Oct 27 '18 12:10 Thebarda

i have the same issue, i need to make my react-select to be required, ex: birth date with year, month ,day dropdown

pipzpadilla avatar Oct 30 '18 07:10 pipzpadilla

This might be a dupe of https://github.com/JedWatson/react-select/issues/1453

IanVS avatar Nov 20 '18 18:11 IanVS

for security reasons if you cannot validate data then you risk your applications being compromised.

springboardStudent avatar Jan 08 '19 00:01 springboardStudent

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. 🙏

gwyneplaine avatar Feb 06 '19 02:02 gwyneplaine

Any update here?

dehghani-mehdi avatar Jun 17 '19 11:06 dehghani-mehdi

+1

Rutulpatel7077 avatar Jul 18 '19 18:07 Rutulpatel7077

Any updates?

AlphaH7 avatar Jul 19 '19 11:07 AlphaH7

Is this repo still getting maintained ? Just curious, should I make PR ?

Rutulpatel7077 avatar Jul 20 '19 15:07 Rutulpatel7077

@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.

claudiuapetrei avatar Jul 22 '19 04:07 claudiuapetrei

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>

image

https://codesandbox.io/s/react-select-v2-required-input-3xvvb?fontsize=14

In some cases you do need position absolute in style

Rutulpatel7077 avatar Jul 24 '19 18:07 Rutulpatel7077

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:

Screenshot from 2019-11-18 12-15-01

louis-atvero avatar Nov 18 '19 12:11 louis-atvero

Any update on this?

clovis1122 avatar Mar 23 '20 16:03 clovis1122

Any ETA on this?

giancarlobrusca avatar Jul 29 '20 14:07 giancarlobrusca

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 .

AlphaH7 avatar Jul 29 '20 16:07 AlphaH7

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;

m-kiruba avatar Jul 30 '20 10:07 m-kiruba

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;
  }
}

Luiyit avatar Aug 21 '20 14:08 Luiyit

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>
  )
}

Intelliflex avatar Sep 14 '20 00:09 Intelliflex

serously, this has been open for 2 years? 😮

orszaczky avatar Oct 02 '20 05:10 orszaczky