react-treebeard icon indicating copy to clipboard operation
react-treebeard copied to clipboard

How to highlight the searched text?

Open turbowars opened this issue 8 years ago • 3 comments

Is there a way I can handle the search event so that I can highlight the searched text in the result list?

turbowars avatar May 17 '17 17:05 turbowars

This is also highly important to us, would love to see it happening :)

kazazor avatar May 18 '17 12:05 kazazor

I've been wanting that feature too.

I ended up highlighting the results after the component has updated using mark.js, which is a pretty awesome highlighting library supporting tons of useful options.

I'm using a custom this.shouldHighlightResults method because in my usecase I can have thousands of results depending on the query you make (I'm displaying a treeview of a french legal code).

  componentDidUpdate() {
    if (this.markInstance) {
      this.markInstance.unmark();
    }
    // highlight search results
    if (this.shouldHighlightResults(this.state.filter)) {
      const markContext = document.querySelector('.code-toc-container');
      this.markInstance = new Mark(markContext);
      this.markInstance.mark(this.state.filter, {
        acrossElements: true,
        separateWordSearch: false
      });
    }
  }

You can see the highlighting live here: http://code.pensionsmilitaires.com/codes/cpmivg2017?q=Annot%C3%A9

daformat avatar Jun 29 '17 13:06 daformat

@daformat do you have that code in a repo? I like how it looks on the demo site.

baradhili avatar Apr 07 '19 06:04 baradhili