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 components on: https://react-select.com/components and not sure which one would best fit my needs.
From looking at the list of components, I believe the option
component is meant for something like that and would probably work but i'm not sure. Can someone validate my thought?
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.