Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using optionRenderer with Select.Aysnc (react-select)

I can't find in the documentations how to use optionRenderer prop with react-select async (Select.Async)

here is a question that already been answered, but the renderOptions is not being called at all

here is my a snippet of my code:

renderOption = (option) => {
    return (
        <div>
            // for example:
            {option.label}: {option.value}
        </div>
    )
}


<Select.Async
    placeholder={placeholder}
    loadOptions={(inputValue) => this.asyncLoadOptions(inputValue)}
    isClearable
    onChange={(value, e) => {
      this.onDropDownFilterChange(value, e)
    }}
    onMenuScrollToBottom={this.fetchDropDownNextPage}
    defaultOptions={defaultOptions}
    defaultValue={defaultValue}
    styles={this.props.hasError ? customStyles : undefined}
    optionRenderer={this.renderOption}

/>

Here I want to keep the functioality and styles for each dropDown item as is (e.g onMouseOver and so on) I just want to format how the items are shown in the list, so is this the right way to do it? or there no other option than using the components prop.

I was able to achieve the formatting right using the components prop, but I lost the styles, and all the mouse events.

like image 396
Mawaheb Avatar asked Apr 25 '26 07:04

Mawaheb


1 Answers

so for those who are looking for the answer, this is what I ended up using and it does the job: (unrelated code has been removed to keep the snippet concise)

import AsyncSelect  from 'react-select/async';
import { components } from 'react-select';

const Option = props => {
    return (
        <components.Option {...props} >
            {props.data.label}<br/>
            <small style={{color: 'gray'}}>
                {props.data.manufacturerName || 'Unknown'} | {props.data.assetGroupDescription || 'Unknown'}
            </small>
        </components.Option>
    )};

class FilterDropDownMenu extends Component {

render() {
    return (
        <>
            <label htmlFor={id}>{translate(placeholder)}</label>
            <AsyncSelect
                {...this.props}
                isClearable
                onChange={(value, e) => {
                    this.onDropDownFilterChange(value, e)
                }}
                onMenuScrollToBottom={this.fetchDropDownNextPage}
                defaultOptions={defaultOptions}
                defaultValue={defaultValue}
                styles={hasError ? customStyles : undefined}
                components={{ Option }}
            />
        </>
    )
   }
}

This way, I get the formatting that I want, And I don't loose the built in functionality of react-select (mouse events and styling and so on).

like image 71
Mawaheb Avatar answered Apr 27 '26 21:04

Mawaheb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!