How can I use react-select to custom render subtext below each dropdown item?

前端 未结 1 1928
死守一世寂寞
死守一世寂寞 2021-01-21 10:13

I\'m trying to figure out how I can utilize the custom components in react-select to render a dropdown that has items with subtext.

I\'ve looked at each one of the compo

相关标签:
1条回答
  • 2021-01-21 10:52

    React-select V2+ solution:

    You are absolutely right, using Option component will allow you to format each option in the menuList like the follow example:

    const options = [
      {
        label: "text 1",
        subLabel: "subtext 1",
        value: "1"
      },
      {
        label: "text 2",
        subLabel: "subtext 2",
        value: "2"
      },
      {
        label: "text 3",
        subLabel: "subtext 3",
        value: "3"
      },
      {
        label: "text 4",
        subLabel: "subtext 4",
        value: "4"
      }
    ];
    
    const Option = props => {
      return (
        <components.Option {...props}>
          <div>{props.data.label}</div>
          <div style={{ fontSize: 12 }}>{props.data.subLabel}</div>
        </components.Option>
      );
    };
    
    function App() {
      return (
        <div className="App">
          <Select options={options} components={{ Option }} />
        </div>
      );
    }
    

    Here a live example.

    React-select V1 solution:

    Keeping the same structure as the V2 solution, you can achieve to display a custom option element by passing a render function using the props optionRenderer like this:

    class App extends Component {
      renderOption = option => (
        <div>
          <label>{option.label}</label>
          <label style={{ display: "block", color: "gray", fontSize: 12 }}>
            {option.subLabel}
          </label>
        </div>
      );
      render() {
        return (
          <div className="App">
            <Select options={options} optionRenderer={this.renderOption} />
          </div>
        );
      }
    }
    

    Here a live example.

    0 讨论(0)
提交回复
热议问题