Using optionRenderer with Select.Aysnc (react-select)

前提是你 提交于 2021-01-27 12:55:49

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/60634778/using-optionrenderer-with-select-aysnc-react-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!