简体   繁体   中英

React-select: How to display HTML in options

I am wondering if react-select could show html in rendered options. For example if fetched ajax option has <b>text</b> , I would like to see text as bold in the dropdown menu instead of seeing <b>text</b> .

I read the documentation and I didnt find any option for this.

Thank you

I implemented the above solution and it broke the searchable feature. The label expects a string, not an element. -- There is actually a prop/function to do this

formatOptionLabel={function(data) {
  return (
    <span dangerouslySetInnerHTML={{ __html: data.label }} />
  );
}}

Check out this post: React-Select: How to maintain search-ability while passing HTML to the label value in options

你可以依赖 react-select 的optionComponent和 React 的危险optionComponent 特性并给optionComponent一个像这样的组件

const MyOptionComponent = props => <span dangerouslySetInnerHTML={{__html : props.option}} />;

As simple as:

{ value: 'foo', label: <span dangerouslySetInnerHTML={{ __html: 'bar &amp; foo' }} /> }

No option component, no option renderer, just simple jsx.

You can create either a custom optionRenderer or optionComponent for react-select .

I'd recommend you optionRenderer as it is more simple, if you only want to put convert to html. You can see an example here:

https://github.com/jquintozamora/react-taxonomypicker/blob/master/app/src/components/TaxonomyPicker/TaxonomyPicker.tsx#L135-L148

There is another example for optionComponent here (just in case you want extra functionality): https://github.com/JedWatson/react-select/blob/master/examples/src/components/CustomComponents.js#L15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM