Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-select cannot set id

Have a react-select component and the id field does not get set? Is it possible to set an id?

<Select
    id={field}
    className="reqform-project-dropdown"
    {...f.props(field)}
    disabled={
        readOnly ||
        onEdit ||
        f.props(field).read_only
    }
    clearable={false}
    options={this.props.common.tests}
    onChange={this.handleProjChange.bind(this, field,
        f.props(field).multiple,
        'test_req_unique_prefix')}
    labelKey="test_name"
    valueKey="test_req_unique_prefix"
/>

I have resorted to setting the id of the parent div, but it seems silly I can't do it directly for the select.

like image 610
Dan Littlejohn Avatar asked Sep 27 '17 17:09

Dan Littlejohn


People also ask

How do I get the selected ID in react?

You can add an onChange event handler to the select which checks for the selected index and retrieve the id from the selected option. This is a bit of an anti-pattern for React.

How do I store select option value in react?

To select a default option in React, the selected attribute is used in the option element. In React, though, instead of using the selected attribute, the value prop is used on the root select element. So, you can set a default value by passing the value of the option in the value prop of the select input element.

How do I set the default option in select react?

You can use an attribute defaultValue to set the default value in the Select menu If none option is integrated with this attribute first option is selected by default. You can create an Array of the object where you will store all options to be displayed and any single object is passed in the defaultValue attribute.

How do you change no options in react select?

You can define your own NoOptionMessage component: import { components } from 'react-select'; const NoOptionsMessage = props => { return ( <components.


2 Answers

In version >= 2 of react-select, the prop to set the id is called inputId. Use it like this:

<Select inputId="your-custom-id" />
like image 150
Honza Kalfus Avatar answered Oct 16 '22 14:10

Honza Kalfus


You can use the inputProps prop as in the docs.

If what you want is focus when clicking the corresponding label, passing id inside inputProps should work.

<label htmlFor={'fieldId'} />
<Select inputProps={{ id: 'fieldId' }} /> // should be an object
like image 38
cfraser Avatar answered Oct 16 '22 12:10

cfraser