最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React-select: How to display HTML in options - Stack Overflow

programmeradmin3浏览0评论

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

Share Improve this question edited Jul 28, 2020 at 17:53 Full Stack Alien 12.5k2 gold badges26 silver badges39 bronze badges asked Mar 16, 2018 at 13:59 gospodingospodin 1,2014 gold badges25 silver badges44 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8

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

As simple as:

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

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

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

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

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

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

You can rely on the optionComponent prop of react-select and the dangerouslySetInnerHTML feature of React And give to optionComponent a ponent like this

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

评论列表(0)

  1. 暂无评论