Is it possible to display html formatted text in antd table?
Asked Answered
S

2

7

My backend service(elasticsearch percolator) annotates text with html tags to highlight matches.

I can't find a way to display such html data in antd Table.

I've tried Highlighter component, but it applies keywords to whole column, but I need to highlight different words in each row.

link to fiddle

const { Table } = antd

class TableColor extends React.Component {
  constructor (props) {
    super(props)

    this.state = {
        data: []
    }
  }

  componentDidMount() {
    this.setState({
        data: [
        {id:1, name: 'Lazy < bclass="myBackgroundColor">fox</b>', match: 'fox'},
        {id:2, name: '<b class="myBackgroundColor">Dog</b> runs', match: 'Dog'},
        {id:3, name: 'I saw <b class="myBackgroundColor">duck</b>', match: 'duck'}
      ]
    })
  }

  render () {
   const columns = [{
      title: 'ID',
      dataIndex: 'id',
    }, {
      title: 'Name',
      dataIndex: 'name',
    }, {
      title: 'Match',
      dataIndex: 'match',
    }]

    return (
        <div style={{padding: '20px'}}>
        <Table
          columns={columns}
          dataSource={this.state.data}
        />
        </div>
    )
  }
}

ReactDOM.render(<TableColor />, document.querySelector('#app'))
Setaceous answered 22/3, 2019 at 15:33 Comment(0)
A
7

Since it looks like the name column already has highlighted html you could just add a render property to the name column definition that uses dangerouslySetInnerHtml to render the raw html.

...something like:

render: function(html) { return <div dangerouslySetInnerHtml({__html: html}) />

https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml https://ant.design/components/table/#Column

If you wanted to use react-highlight-words you could do the same thing with a render property but use the second argument passed to that function to get the .match property of the record and use that as the highlighted word.

Aardvark answered 24/3, 2019 at 15:33 Comment(0)
S
0

Yes. Just use dangerouslySetInnerHTML in render function like:

render: (html:any) => {return <div dangerouslySetInnerHTML={{__html: html}} />}
Sarcous answered 22/2 at 9:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.