React component to highlight words within a larger body of text

Overview

React component to highlight words within a larger body of text.

Check out a demo here.

Usage

To use it, just provide it with an array of search terms and a body of text to highlight.

Try this example in Code Sandbox.

import React from "react";
import ReactDOM from "react-dom";
import Highlighter from "react-highlight-words";

ReactDOM.render(
  <Highlighter
    highlightClassName="YourHighlightClass"
    searchWords={["and", "or", "the"]}
    autoEscape={true}
    textToHighlight="The dog is chasing the cat. Or perhaps they're just playing?"
  />,
  document.getElementById("root")
);

And the Highlighter will mark all occurrences of search terms within the text:

screen shot 2015-12-19 at 8 23 43 am

Props

Property Type Required? Description
activeClassName String The class name to be applied to an active match. Use along with activeIndex
activeIndex Number Specify the match index that should be actively highlighted. Use along with activeClassName
activeStyle Object The inline style to be applied to an active match. Use along with activeIndex
autoEscape Boolean Escape characters in searchWords which are meaningful in regular expressions
className String CSS class name applied to the outer/wrapper <span>
caseSensitive Boolean Search should be case sensitive; defaults to false
findChunks Function Use a custom function to search for matching chunks. This makes it possible to use arbitrary logic when looking for matches. See the default findChunks function in highlight-words-core for signature. Have a look at the custom findChunks example on how to use it.
highlightClassName String or Object CSS class name applied to highlighted text or object mapping search term matches to class names.
highlightStyle Object Inline styles applied to highlighted text
highlightTag Node Type of tag to wrap around highlighted matches; defaults to mark but can also be a React element (class or functional)
sanitize Function Process each search word and text to highlight before comparing (eg remove accents); signature (text: string): string
searchWords Array<String | RegExp> Array of search words. String search terms are automatically cast to RegExps unless autoEscape is true.
textToHighlight String Text to highlight matches in
unhighlightClassName String CSS class name applied to unhighlighted text
unhighlightStyle Object Inline styles applied to unhighlighted text
* any Any other props (such as title or data-*) are applied to the outer/wrapper <span>

Custom highlight tag

By default this component uses an HTML Mark Text element (<mark>) to wrap matched text, but you can inject a custom tag using the highlightTag property. This tag should be a React component that accepts the following properties:

Property Type Description
children String Text to be highlighted
highlightIndex Number Index of matched text

For example:

const Highlight = ({ children, highlightIndex }) => (
  <strong className="highlighted-text">{children}</strong>
);

Installation

yarn add react-highlight-words
npm i --save react-highlight-words

License

MIT License - fork, modify and use however you want.

Comments
  • Expose chunk, chunkIndex, and highlightIndex to highlightTag render prop

    Expose chunk, chunkIndex, and highlightIndex to highlightTag render prop

    This change exposes the chunk, index as chunkIndex, and highlightCount as highlightIndex to the HighlightTag render prop. This is useful if a user would like to apply custom styling/colors to the chunks. It could be used like this for example:

    const getHighlightTag = () => ({ children, highlightIndex }) => {
        const backgroundColors: {
            0: 'green',
            1: 'red',
            2: 'blue
        }
    
        return (
            <mark backgroundColor={backgroundColors[highlightIndex]}>
                {children}
            </mark>
        );
    };
    
    
    <Highlighter
        highlightTag={getHighlightTag()}
        searchWords={[ 'hello', 'highlight', 'text' ]}
        textToHighlight={'hello, highlight this text'}
    />
    

    The chunk and chunkIndex props are not necessary for the above example, but I thought they may be useful for someone

    opened by pkmoran 10
  • Multiple colors

    Multiple colors

    This change introduces a new prop called textColors. This new prop is a mapping of words to css classes and is used to apply these classes to the words.

    For example: { the: 'green', of: 'blue', hello: 'orange' }

    In the example, instances of the will have the class green applied to them instead of highlightClassName.

    Note: I had trouble running the tests due to an npm install problem, probably with phantomjs. I'm happy to take some advice on that to make sure that the tests still pass, because I was unable to do that.

    opened by Chris-Gillis 5
  • feat: Add unhighlightTag prop

    feat: Add unhighlightTag prop

    Description

    This PR adds ability to render custom HTML tags / React Nodes instead of defaulting to <span> element.

    Problem

    Defaulting to <span> is a good idea and must have, but sometimes we have edge cases where you need to pass custom React nodes in order to provide additional functionalities. Please see the Use Case below.

    Use Case

    Should be able to render <a> tags whenever necessary or pass React components (such as <Linkify>: https://github.com/tasti/react-linkify) to render the links properly.

    opened by kaungmyatlwin 3
  • Add `highlightWrapper` which accepts a function to wrap the highlighted text in.

    Add `highlightWrapper` which accepts a function to wrap the highlighted text in.

    For example, we can pass in the following function:

    ({ children }) => {
      return (
        <div onClick={doSomething()}>{children}</div>
      );
    }
    

    This would enable custom behavior to be added to highlighted words.

    opened by camden 3
  • Add support for pre-compare function

    Add support for pre-compare function

    For what I am doing I needed the ability to pass a pre-comparison function, in order that accented characters were matched by unaccented characters. Submitting this PR in case this is useful to you. Happy to modify if you want.

    opened by nathanpower 3
  • Do not include .babelrc in npm package

    Do not include .babelrc in npm package

    An alternative solution to #19. I'm guessing @untone is dealing with the same problem that I am - an inability to use react-highlight-words since it's .babelrc is for Babel 5 and we're using Babel 6.

    See https://github.com/reactjs/redux/issues/1033 and https://github.com/gaearon/redux-thunk/pull/44 if more justification is required.

    opened by markwoon 2
  • Reduce library size (by 37x)

    Reduce library size (by 37x)

    I was running webpack-bundle-size-analyzer investigating why my bundle size was getting so big and I noticed your library was taking more space than React itself ! With some digging I figured you are actually including React with this package which isn't the expected behavior when React is already a dependency of the package.

    This PR adds adds React as an externals (see http://webpack.github.io/docs/library-and-externals.html) so that it's not included. main.js is now almost 37x smaller :

    Before:

    ~/react-highlight-words $ ls -la dist/main.js
    -rw-r--r--  1 loic  staff  695657 May 10 17:31 dist/main.js
    

    After:

     ~/react-highlight-words $ ls -la dist/main.js
    -rw-r--r--  1 loic  staff  18826 May 10 17:34 dist/main.js
    

    It also adds a .npmignore so unused files don't get included in the npm package

    opened by chollier 2
  • Moved prop-types to devDependencies and enabled dist uglification

    Moved prop-types to devDependencies and enabled dist uglification

    A couple of changes:

    • prop-types was in the dependencies section of package.json
    • build was not generating a uglified output (so 50K instead of 15). About this I'm still wondering if this was intentional or not.
    opened by keul 1
  • Emphasise RegExp behaviour of

    Emphasise RegExp behaviour of "searchWords" in readme

    I found it rather surprising that the searchWords are treated as RegExp by default. This PR tweaks the Readme slightly so that new users are less likely to be cut on this sharp edge.

    Issue #12 discusses changing this default and concludes "changing the default would require a major release"

    opened by RichardBradley 1
  • Combine highlights of overlapping matches

    Combine highlights of overlapping matches

    Fixes #1 by doing a pass over the text to find all matching "chunks" for each search word. It then does a pass over these chunks to merge the ones which are overlapping. Finally, given a blob of text and a set of merged chunks, it creates chunks for each of the non-matching portions of the text. This resulting collection of matching and non-matching chunks then get used to identify each portion of the text as either a highlighted or a non-highlighted portion.

    Notes on tests: I must apologise for not taking the time to learn whatever the testing framework you are using. I had some troubles getting it to run on my ArchLinux laptop for some reason. Anyhow, I did create a set of unit tests, and I tried to make it clear where each test starts/finishes by running them in an anonymous function. Hopefully it should be easy to extract these into proper tests for the JS testing framework of your choice.

    In order to run these tests, I have a silly branch with an extra commit. The tip of that branch runs the tests each time the Highlighter module is imported, and prints to the console if there are errors.

    opened by pserwylo 1
  • feat: provide basic support of React 18

    feat: provide basic support of React 18

    It's a stepping stone PR that makes it possible to use the library with React 18:

    opened by sergei-startsev 0
Releases(v0.18.0)
  • v0.18.0(Apr 13, 2022)

Owner
Brian Vaughn
React JS core team at @facebook; formerly at @treasure-data and @google.
Brian Vaughn
🔦 Vue component for highlight multiple instances of a word

vue-highlight-text Vue component for highlight multiple instances of a word Installation # with yarn yarn add vue-highlight-text # with npm npm insta

Chanwit Piromplad 56 Dec 15, 2022
clean-react is basically React without all the garbage 🗑️

clean-react-app clean-react-app is basically React without all the garbage ??️ It generates a create-react-app without all the garbage. A clean app to

Yassine 1 Jan 7, 2022
Generates a cloud out of the words.

VueWordCloud Generates a cloud out of the words. demo Try it out! setup npm npm i vuewordcloud ES module Register the component globally. import Vue f

Sergej Sintschilin 336 Jan 3, 2023
Operation-words - This is power of the vectors.

Wikipedia日本語版のデータから、単語をベクトル化しました。単語のもつ意味を足し引きし、どんな結果が得られるか見てみましょう。 NuxtJSを使用したWebアプリのフロントエンドです。 バックエンドはこちら ビルド方法 パッケージをインストールしておきます。 yarn あとはNuxtJSに頼っ

Denden 0 Jan 31, 2022
NPM package: a 3D rolling sphere of words following your mouse movements

wordsphere NPM package: a 3D rolling sphere of words following your mouse moveme

Ilan Azoulay 2 Jun 28, 2022
A game in which you try to find associative words (like tires, seats, and wheel of a car--the source word) of a source word

Find Associative Words A game in which you try to find associative words (like tires, seats, and wheel of a car--the source word) of a source word. Th

EGGSY 10 Oct 2, 2022
Syntax highlighting with highlight.js for Vue.js 2.x

vue-highlightjs Vue.js syntax highlighting made easy, using highlight.js. Quickstart Installation Simply install the npm package vue-highlightjs: npm

Chris Hager 335 Nov 25, 2022
Easy @mention, #hashtag and URL highlight for Vue 2.x

vue-highlights Easy @mention, #hashtag and URL highlight for Vue 2.x Installation You can install via npm or yarn: npm install --save vue-highlights y

Pedro G. Galaviz 16 Nov 17, 2022
Vue 3 directive for highlight.js

Vue 3 directive for highlight.js

null 7 May 24, 2022
Vue component to trap the focus within a DOM element

focus-trap-vue Vue component to trap the focus within a DOM element Installation For Vue 2 npm install focus-trap focus-trap-vue For Vue 3 npm install

Eduardo San Martin Morote 169 Jan 1, 2023
Content-theme-blog-minimal is a standalone theme for creating your blog within minutes!

content-theme-blog-minimal content-theme-blog-minimal is a standalone theme for creating your blog within minutes! Demo: https://dumptyd.github.io/con

Saad 12 Aug 28, 2022
Diagram component for vue.js, inspired by react-diagrams

vue-diagrams Diagram component for vue.js, inspired by react-diagrams Generated using vue-cli-template-library. Installation npm install vue-diagrams

Gwenael Pluchon 248 Dec 7, 2022
A beautiful chat rooms component made with Vue.js - compatible with Vue, React & Angular

vue-advanced-chat Vue 3 compatibility ?? Features Vue, Angular & React compatibility Customizeable realtime chat messaging Backend agnostic Images, vi

Antoine Dupont 1.1k Jan 6, 2023
A web component to use Phaser Framework CE (Community Edition) with Angular, React, Vue, etc 🎮

IonPhaser CE (Community Edition) Web Component built with Stencil.js to integrate Phaser CE (Community Edition) with any other framework. Inspired by

Proyecto 26 11 Sep 8, 2022
Wrapper of Inversify to inject your dependencies in the components, made with TypeScript and compatible with Vue, React and other component libraries.

Inversify Props This package is a wrapper of Inversify to simplify how inject your dependencies with property decorators in the components, made with

Quique Fdez Guerra 78 Jan 31, 2023
Vue component that simulates a user typing, selecting, and erasing text.

Vue component that simulates a user typing, selecting, and erasing text. Play with vue-typer in this interactive demo. Getting Started Usage Props tex

null 778 Dec 28, 2022
A simple component that truncates your text and adds a 'Read More/Show Less' clickable.

vue-truncate-collapsed A simple Vue 2 Component that's truncate your text and adds a "Read Me/Show Less" clickable. Getting Started NPM $ npm install

Johnny Cavalcante 106 Feb 5, 2022
The same features you expect from `input type="text"` but in a `contenteditable` Vue component

vue-input-contenteditable Make beautiful inputs without the restrictions of input[type='text']. A Vue component wrapper for contenteditable with all t

Cobertos / Samantha 19 Oct 12, 2022