├── .babelrc ├── .gitignore ├── .npmignore ├── LICENSE ├── README.md ├── circle.yml ├── karma.conf.js ├── package.json ├── src ├── Highlighter.example.css ├── Highlighter.example.js ├── Highlighter.js ├── Highlighter.test.js ├── index.js ├── test-utils.js └── tests.js ├── webpack.config.dev.js ├── webpack.config.dist.base.js ├── webpack.config.dist.cjs.js ├── webpack.config.dist.umd.js ├── webpack.config.test.js ├── webpack.config.website.js ├── website ├── Application.css ├── Application.js ├── index.css ├── index.html └── index.js └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "stage": 0, 3 | "env": { 4 | "development": { 5 | "plugins": ["react-transform"], 6 | "extra": { 7 | "react-transform": { 8 | "transforms": [{ 9 | "transform": "react-transform-hmr", 10 | "imports": ["react"], 11 | "locals": ["module"] 12 | }] 13 | } 14 | } 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | /log/* 3 | !/log/.keep 4 | /tmp 5 | *.log 6 | 7 | # Dependency directory 8 | node_modules 9 | 10 | # Test stuff 11 | coverage 12 | 13 | # OS X 14 | .DS_Store 15 | 16 | # Misc 17 | node_modules 18 | npm-debug.log 19 | build 20 | dist 21 | 22 | # IDE 23 | .idea 24 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | website 2 | node_modules 3 | karma.conf.js 4 | src 5 | webpack* 6 | .idea 7 | .babelrc 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Treasure Data 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | React component to highlight words within a larger body of text. 4 | 5 | Check out a demo [here](https://bvaughn.github.io/react-highlight-words). 6 | 7 | ## Usage 8 | 9 | To use it, just provide it with an array of search terms and a body of text to highlight. 10 | 11 | [Try this example in Code Sandbox.](https://codesandbox.io/s/5v8yqoxv7k) 12 | 13 | ```jsx 14 | import React from "react"; 15 | import { createRoot } from "react-dom/client"; 16 | import Highlighter from "react-highlight-words"; 17 | 18 | const root = createRoot(document.getElementById("root")); 19 | root.render( 20 | 26 | ); 27 | ``` 28 | 29 | And the `Highlighter` will mark all occurrences of search terms within the text: 30 | 31 | 32 | 33 | ## Props 34 | 35 | | Property | Type | Required? | Description | 36 | |------------------------|-----------------------------|:---------:|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 37 | | `activeClassName` | String | | The class name to be applied to an active match. Use along with `activeIndex` | 38 | | `activeIndex` | Number | | Specify the match index that should be actively highlighted. Use along with `activeClassName` | 39 | | `activeStyle` | Object | | The inline style to be applied to an active match. Use along with `activeIndex` | 40 | | `autoEscape` | Boolean | | Escape characters in `searchWords` which are meaningful in regular expressions | 41 | | `className` | String | | CSS class name applied to the outer/wrapper `` | 42 | | `caseSensitive` | Boolean | | Search should be case sensitive; defaults to `false` | 43 | | `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](https://github.com/bvaughn/highlight-words-core) for signature. Have a look at the [custom findChunks example](https://codesandbox.io/s/k20x3ox31o) on how to use it. | 44 | | `highlightClassName` | String or Object | | CSS class name applied to highlighted text or object mapping search term matches to class names. | 45 | | `highlightStyle` | Object | | Inline styles applied to highlighted text | 46 | | `highlightTag` | Node or String | | Type of tag to wrap around highlighted matches. Defaults to `mark` but can also be a React component (class or functional) | 47 | | `sanitize` | Function | | Process each search word and text to highlight before comparing (eg remove accents); signature `(text: string): string` | 48 | | `searchWords` | Array | ✓ | Array of search words. String search terms are automatically cast to RegExps unless `autoEscape` is true. | 49 | | `textToHighlight` | String | ✓ | Text to highlight matches in | 50 | | `unhighlightClassName` | String | | CSS class name applied to unhighlighted text | 51 | | `unhighlightStyle` | Object | | Inline styles applied to unhighlighted text | 52 | | `unhighlightTag` | Node or String | | Type of tag applied to unhighlighted parts. Defaults to `span` but can also be a React component (class or functional) | 53 | | * | any | | Any other props (such as `title` or `data-*`) are applied to the outer/wrapper `` | 54 | 55 | ## Custom highlight tag 56 | 57 | By default, this component uses an HTML Mark Text element (``) to wrap matched text, but you can inject a custom 58 | tag using the `highlightTag` property. This tag should be a React component that accepts the following properties: 59 | 60 | | Property | Type | Description | 61 | |------------------|--------|------------------------| 62 | | `children` | String | Text to be highlighted | 63 | | `highlightIndex` | Number | Index of matched text | 64 | 65 | For example: 66 | 67 | ```js 68 | const Highlight = ({ children, highlightIndex }) => ( 69 | {children} 70 | ); 71 | ``` 72 | 73 | ## Installation 74 | 75 | ``` 76 | yarn add react-highlight-words 77 | ``` 78 | 79 | ``` 80 | npm i react-highlight-words 81 | ``` 82 | 83 | ## License 84 | 85 | MIT License - fork, modify and use however you want. 86 | -------------------------------------------------------------------------------- /circle.yml: -------------------------------------------------------------------------------- 1 | general: 2 | branches: 3 | ignore: 4 | - gh-pages 5 | machine: 6 | node: 7 | version: v5.1.0 8 | 9 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | module.exports = function (config) { 2 | config.set({ 3 | browsers: ['PhantomJS2'], 4 | frameworks: ['mocha'], 5 | files: ['src/tests.js'], 6 | preprocessors: { 7 | 'src/tests.js': ['webpack', 'sourcemap'] 8 | }, 9 | junitReporter: { 10 | outputDir: (process.env.CIRCLE_TEST_REPORTS || 'public') + '/karma', 11 | suite: 'karma' 12 | }, 13 | singleRun: true, 14 | plugins: [ 15 | require('karma-mocha'), 16 | require('karma-webpack'), 17 | require('karma-spec-reporter'), 18 | require('karma-junit-reporter'), 19 | require('karma-sourcemap-loader'), 20 | require('karma-phantomjs2-launcher') 21 | ], 22 | webpack: require('./webpack.config.test') 23 | }) 24 | } 25 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-highlight-words", 3 | "version": "0.21.0", 4 | "description": "React component to highlight words within a larger body of text", 5 | "main": "dist/main.js", 6 | "scripts": { 7 | "build": "npm run build:website && npm run build:dist", 8 | "build:website": "npm run clean:website && cross-env NODE_ENV=production webpack --config webpack.config.website.js -p --bail", 9 | "build:dist": "npm run clean:dist && cross-env NODE_ENV=production webpack --config webpack.config.dist.cjs.js --bail && cross-env NODE_ENV=production webpack --config webpack.config.dist.umd.js --bail", 10 | "clean": "npm run clean:website && npm run clean:dist", 11 | "clean:website": "rimraf build", 12 | "clean:dist": "rimraf dist", 13 | "deploy": "gh-pages -d build", 14 | "lint": "standard", 15 | "prebuild": "npm run lint", 16 | "prepublishOnly": "npm run build", 17 | "postpublish": "npm run deploy", 18 | "start": "webpack-dev-server --hot --inline --config webpack.config.dev.js", 19 | "test": "cross-env NODE_ENV=test karma start", 20 | "watch": "watch 'clear && npm run lint -s && npm run test -s' src" 21 | }, 22 | "repository": { 23 | "type": "git", 24 | "url": "git+https://github.com/bvaughn/react-highlight-words.git" 25 | }, 26 | "author": "Brian Vaughn", 27 | "license": "MIT", 28 | "bugs": { 29 | "url": "https://github.com/bvaughn/react-highlight-words/issues" 30 | }, 31 | "homepage": "https://github.com/bvaughn/react-highlight-words#readme", 32 | "keywords": [ 33 | "react", 34 | "reactjs", 35 | "react-component", 36 | "highlighter", 37 | "highlight", 38 | "text", 39 | "words", 40 | "matches", 41 | "substring", 42 | "occurrences", 43 | "search" 44 | ], 45 | "standard": { 46 | "parser": "babel-eslint", 47 | "ignore": [ 48 | "build", 49 | "dist", 50 | "node_modules" 51 | ], 52 | "global": [ 53 | "afterAll", 54 | "afterEach", 55 | "beforeAll", 56 | "beforeEach", 57 | "describe", 58 | "it", 59 | "jasmine" 60 | ] 61 | }, 62 | "devDependencies": { 63 | "babel": "^5.8.34", 64 | "babel-core": "^5.8.34", 65 | "babel-eslint": "^4.1.6", 66 | "babel-loader": "^5.4.0", 67 | "babel-plugin-react-transform": "^1.1.1", 68 | "cross-env": "^5.1.3", 69 | "css-loader": "^0.23.0", 70 | "cssnext": "^1.8.4", 71 | "cssnext-loader": "^1.0.1", 72 | "expect.js": "^0.3.1", 73 | "gh-pages": "^0.8.0", 74 | "html-webpack-plugin": "^1.7.0", 75 | "karma": "^0.13.15", 76 | "karma-junit-reporter": "^0.3.8", 77 | "karma-mocha": "^0.2.1", 78 | "karma-phantomjs2-launcher": "^0.3.2", 79 | "karma-sourcemap-loader": "^0.3.6", 80 | "karma-spec-reporter": "0.0.23", 81 | "karma-webpack": "^1.7.0", 82 | "latinize": "^0.2.0", 83 | "lodash": "^4.17.10", 84 | "mocha": "^2.3.4", 85 | "phantomjs2": "^2.0.2", 86 | "react": "^19.0.0", 87 | "react-dom": "^19.0.0", 88 | "react-transform-hmr": "^1.0.1", 89 | "rimraf": "^2.4.4", 90 | "standard": "^5.4.1", 91 | "style-loader": "^0.13.0", 92 | "watch": "^0.16.0", 93 | "webpack": "^1.12.9", 94 | "webpack-dev-server": "^1.14.0", 95 | "worker-loader": "^0.7.0" 96 | }, 97 | "dependencies": { 98 | "highlight-words-core": "^1.2.0", 99 | "memoize-one": "^4.0.0" 100 | }, 101 | "peerDependencies": { 102 | "react": "^0.14.0 || ^15.0.0 || ^16.0.0-0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/Highlighter.example.css: -------------------------------------------------------------------------------- 1 | .Header { 2 | margin: 0 0 .5rem; 3 | font-size: 1.25em; 4 | font-weight: normal; 5 | } 6 | 7 | .Input { 8 | width: 100%; 9 | border: 1px solid #78909c; 10 | line-height: 1.4; 11 | padding: .3em .5em; 12 | border-radius: .3em; 13 | margin-bottom: 1em; 14 | font-size: 1em; 15 | } 16 | 17 | .Highlight { 18 | background-color: #ffd54f; 19 | } 20 | 21 | .Active { 22 | background-color: #f48f42; 23 | } 24 | 25 | .Footer { 26 | margin-bottom: 0; 27 | } 28 | 29 | .Row { 30 | display: flex; 31 | flex-direction: row; 32 | align-items: flex-start; 33 | justify-content: space-between; 34 | } 35 | 36 | .FirstColumn, 37 | .SecondColumn { 38 | flex: 1 1 auto; 39 | } 40 | 41 | .FirstColumn { 42 | margin-right: 0.5rem; 43 | } 44 | 45 | .SecondColumn { 46 | margin-left: 0.5rem; 47 | } 48 | -------------------------------------------------------------------------------- /src/Highlighter.example.js: -------------------------------------------------------------------------------- 1 | import latinize from 'latinize' 2 | import React, { Component } from 'react' 3 | import Highlighter from './Highlighter' 4 | import styles from './Highlighter.example.css' 5 | 6 | export default class HighlighterExample extends Component { 7 | constructor (props) { 8 | super(props) 9 | 10 | this.state = { 11 | searchText: 'and or the', 12 | textToHighlight: `When in the Course of human events it becomes necessary for one people to dissolve the political bands which have connected them with another and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.`, 13 | activeIndex: -1, 14 | caseSensitive: false 15 | } 16 | } 17 | render () { 18 | const { ...props } = this.props 19 | const { activeIndex, caseSensitive, searchText, textToHighlight } = this.state 20 | const searchWords = searchText.split(/\s/).filter(word => word) 21 | 22 | return ( 23 | 24 | 25 | 26 | 27 | Search terms 28 | 29 | this.setState({ searchText: event.target.value })} 34 | /> 35 | 36 | 37 | 38 | Active Index 39 | 40 | this.setState({ activeIndex: parseInt(event.target.value, 10) })} 45 | type='number' 46 | /> 47 | 48 | 49 | 50 | Case Sensitive? 51 | 52 | this.setState({ caseSensitive: event.target.checked })} 57 | type='checkbox' 58 | /> 59 | 60 | 61 | 62 | 63 | Body of Text 64 | 65 | this.setState({ textToHighlight: event.target.value })} 70 | /> 71 | 72 | 73 | Output 74 | 75 | 76 | 87 | 88 | 89 | 90 | View the source 91 | 92 | 93 | 94 | ) 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/Highlighter.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import { findAll } from 'highlight-words-core' 3 | import { createElement } from 'react' 4 | import memoizeOne from 'memoize-one' 5 | 6 | /** 7 | * Highlighter component 8 | * @param {object} props - Component properties 9 | * @param {string} [props.activeClassName] - The class name to be applied to an active match. Use along with `activeIndex`. 10 | * @param {number} [props.activeIndex] - Specify the match index that should be actively highlighted. Use along with `activeClassName`. 11 | * @param {object} [props.activeStyle] - The inline style to be applied to an active match. Use along with `activeIndex`. 12 | * @param {boolean} [props.autoEscape] - Escape characters in searchWords which are meaningful in regular expressions. 13 | * @param {string} [props.className] - CSS class name applied to the outer/wrapper ``. 14 | * @param {(options: object) => Array<{start: number, end: number}>} [props.findChunks] - Use a custom function to search for matching chunks. See the default `findChunks` function in `highlight-words-core` for signature. 15 | * @param {string|object} [props.highlightClassName] - CSS class name applied to highlighted text or object mapping search term matches to class names. 16 | * @param {object} [props.highlightStyle] - Inline styles applied to highlighted text. 17 | * @param {React.ComponentType|string} [props.highlightTag] - Type of tag to wrap around highlighted matches. Defaults to `mark` but can also be a React component (class or functional). 18 | * @param {(text: string) => string} [props.sanitize] - Process each search word and text to highlight before comparing. 19 | * @param {Array} props.searchWords - Array of search words. String search terms are automatically cast to RegExps unless `autoEscape` is true. 20 | * @param {string} props.textToHighlight - The text to highlight matches in. 21 | * @param {React.ComponentType|string} [props.unhighlightTag] - Type of tag applied to unhighlighted parts. Defaults to `span` but can also be a React component (class or functional). 22 | * @param {string} [props.unhighlightClassName] - CSS class name applied to unhighlighted text. 23 | * @param {object} [props.unhighlightStyle] - Inline styles applied to the unhighlighted text. 24 | * @param {object} [props.rest] - Additional attributes passed to the outer `` element. 25 | */ 26 | export default function Highlighter ({ 27 | activeClassName = '', 28 | activeIndex = -1, 29 | activeStyle, 30 | autoEscape, 31 | caseSensitive = false, 32 | className, 33 | findChunks, 34 | highlightClassName = '', 35 | highlightStyle = {}, 36 | highlightTag = 'mark', 37 | sanitize, 38 | searchWords, 39 | textToHighlight, 40 | unhighlightTag = 'span', 41 | unhighlightClassName = '', 42 | unhighlightStyle, 43 | ...rest 44 | }) { 45 | const chunks = findAll({ 46 | autoEscape, 47 | caseSensitive, 48 | findChunks, 49 | sanitize, 50 | searchWords, 51 | textToHighlight 52 | }) 53 | const HighlightTag = highlightTag 54 | let highlightIndex = -1 55 | let highlightClassNames = '' 56 | let highlightStyles 57 | 58 | const lowercaseProps = object => { 59 | const mapped = {} 60 | for (let key in object) { 61 | mapped[key.toLowerCase()] = object[key] 62 | } 63 | return mapped 64 | } 65 | const memoizedLowercaseProps = memoizeOne(lowercaseProps) 66 | 67 | return createElement('span', { 68 | className, 69 | ...rest, 70 | children: chunks.map((chunk, index) => { 71 | const text = textToHighlight.substr(chunk.start, chunk.end - chunk.start) 72 | 73 | if (chunk.highlight) { 74 | highlightIndex++ 75 | 76 | let highlightClass 77 | if (typeof highlightClassName === 'object') { 78 | if (!caseSensitive) { 79 | highlightClassName = memoizedLowercaseProps(highlightClassName) 80 | highlightClass = highlightClassName[text.toLowerCase()] 81 | } else { 82 | highlightClass = highlightClassName[text] 83 | } 84 | } else { 85 | highlightClass = highlightClassName 86 | } 87 | 88 | const isActive = highlightIndex === +activeIndex 89 | 90 | highlightClassNames = `${highlightClass} ${isActive ? activeClassName : ''}` 91 | highlightStyles = isActive === true && activeStyle != null 92 | ? Object.assign({}, highlightStyle, activeStyle) 93 | : highlightStyle 94 | 95 | const props = { 96 | children: text, 97 | className: highlightClassNames, 98 | key: index, 99 | style: highlightStyles 100 | } 101 | 102 | // Don't attach arbitrary props to DOM elements; this triggers React DEV warnings (https://fb.me/react-unknown-prop) 103 | // Only pass through the highlightIndex attribute for custom components. 104 | if (typeof HighlightTag !== 'string') { 105 | props.highlightIndex = highlightIndex 106 | } 107 | 108 | return createElement(HighlightTag, props) 109 | } else { 110 | return createElement(unhighlightTag, { 111 | children: text, 112 | className: unhighlightClassName, 113 | key: index, 114 | style: unhighlightStyle 115 | }) 116 | } 117 | }) 118 | }) 119 | } 120 | -------------------------------------------------------------------------------- /src/Highlighter.test.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable react/prop-types */ // TODO: replace standard with prettier 2 | import React from 'react' 3 | import Highlighter from './Highlighter' 4 | import { render } from './test-utils' 5 | import expect from 'expect.js' 6 | import latinize from 'latinize' 7 | 8 | describe('Highlighter', () => { 9 | const HIGHLIGHT_CLASS = 'customHighlightClass' 10 | const HIGHLIGHT_QUERY_SELECTOR = `.${HIGHLIGHT_CLASS}` 11 | const UNHIGHLIGHT_CLASS = 'customUnhighlightClass' 12 | const UNHIGHLIGHT_QUERY_SELECTOR = `.${UNHIGHLIGHT_CLASS}` 13 | 14 | function getHighlighterChildren ({ 15 | autoEscape, 16 | activeClassName, 17 | activeStyle, 18 | activeIndex, 19 | caseSensitive, 20 | findChunks, 21 | highlightStyle, 22 | highlightTag, 23 | sanitize, 24 | searchWords, 25 | textToHighlight, 26 | unhighlightTag, 27 | unhighlightStyle, 28 | highlightClassName, 29 | ...rest 30 | }) { 31 | return new Promise(resolve => { 32 | const callback = () => { 33 | const span = render._mountNode.children[0].children[0] 34 | resolve(span) 35 | } 36 | render( 37 | 38 | 56 | 57 | ) 58 | }) 59 | } 60 | 61 | let consoleError 62 | 63 | beforeEach(() => { 64 | consoleError = console.error 65 | 66 | // React DEV warnings should fail tests 67 | console.error = function (message) { 68 | consoleError.apply(console, arguments) 69 | throw new Error(message) 70 | } 71 | }) 72 | 73 | afterEach(() => { 74 | console.error = consoleError 75 | }) 76 | 77 | it('should properly handle an empty array for searchWords', async () => { 78 | const node = await getHighlighterChildren({ 79 | searchWords: [], 80 | textToHighlight: 'This is text' 81 | }) 82 | expect(node.children.length).to.equal(1) 83 | expect(node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR).length).to.equal(0) 84 | expect(node.textContent).to.eql('This is text') 85 | }) 86 | 87 | it('should properly handle an empty string for searchWords', async () => { 88 | const node = await getHighlighterChildren({ 89 | searchWords: [''], 90 | textToHighlight: 'This is text' 91 | }) 92 | expect(node.children.length).to.equal(1) 93 | expect(node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR).length).to.equal(0) 94 | expect(node.textContent).to.eql('This is text') 95 | }) 96 | 97 | it('should properly handle empty textToHighlight', async () => { 98 | const node = await getHighlighterChildren({ 99 | searchWords: ['search'], 100 | textToHighlight: '' 101 | }) 102 | expect(node.children.length).to.equal(0) 103 | expect(node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR).length).to.equal(0) 104 | expect(node.textContent).to.eql('') 105 | }) 106 | 107 | it('should highlight searchText words that exactly match words in textToHighlight', async () => { 108 | const node = await getHighlighterChildren({ 109 | searchWords: ['text'], 110 | textToHighlight: 'This is text' 111 | }) 112 | expect(node.children.length).to.equal(2) 113 | const matches = node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR) 114 | expect(matches.length).to.equal(1) 115 | expect(matches[0].textContent).to.eql('text') 116 | }) 117 | 118 | it('should handle unclosed parentheses when autoEscape prop is truthy', async () => { 119 | const node = await getHighlighterChildren({ 120 | autoEscape: true, 121 | searchWords: ['('], 122 | textToHighlight: '(This is text)' 123 | }) 124 | expect(node.children.length).to.equal(2) 125 | expect(node.children[0].textContent).to.equal('(') 126 | expect(node.children[1].textContent).to.equal('This is text)') 127 | const matches = node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR) 128 | expect(matches.length).to.equal(1) 129 | expect(matches[0].textContent).to.eql('(') 130 | }) 131 | 132 | it('should highlight searchText words that partial-match text in textToHighlight', async () => { 133 | const node = await getHighlighterChildren({ 134 | searchWords: ['Th'], 135 | textToHighlight: 'This is text' 136 | }) 137 | expect(node.children.length).to.equal(2) 138 | const matches = node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR) 139 | expect(matches.length).to.equal(1) 140 | expect(matches[0].textContent).to.eql('Th') 141 | expect(node.children[0].textContent).to.equal('Th') 142 | expect(node.children[1].textContent).to.equal('is is text') 143 | }) 144 | 145 | it('should highlight multiple occurrences of a searchText word', async () => { 146 | const node = await getHighlighterChildren({ 147 | searchWords: ['is'], 148 | textToHighlight: 'This is text' 149 | }) 150 | expect(node.children.length).to.equal(5) 151 | expect(node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR).length).to.equal(2) 152 | expect(node.textContent).to.eql('This is text') 153 | expect(node.children[0].textContent).to.equal('Th') 154 | expect(node.children[1].textContent).to.equal('is') 155 | expect(node.children[2].textContent).to.equal(' ') 156 | expect(node.children[3].textContent).to.equal('is') 157 | expect(node.children[4].textContent).to.equal(' text') 158 | }) 159 | 160 | it('should highlight multiple searchText words', async () => { 161 | const node = await getHighlighterChildren({ 162 | searchWords: ['This', 'text'], 163 | textToHighlight: 'This is text' 164 | }) 165 | expect(node.children.length).to.equal(3) 166 | expect(node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR).length).to.equal(2) 167 | expect(node.textContent).to.eql('This is text') 168 | expect(node.children[0].textContent).to.equal('This') 169 | expect(node.children[1].textContent).to.equal(' is ') 170 | expect(node.children[2].textContent).to.equal('text') 171 | }) 172 | 173 | it('should handle Regex searchText', async () => { 174 | const node = await getHighlighterChildren({ 175 | searchWords: [/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/, 'This'], 176 | textToHighlight: 'This is my phone (123) 456 7899' 177 | }) 178 | expect(node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR).length).to.equal(2) 179 | expect(node.textContent).to.eql('This is my phone (123) 456 7899') 180 | expect(node.children[0].textContent).to.equal('This') 181 | expect(node.children[1].textContent).to.equal(' is my phone ') 182 | expect(node.children[2].textContent).to.equal('(123) 456 7899') 183 | }) 184 | 185 | it('should match terms in a case insensitive way but show their case-sensitive representation', async () => { 186 | const node = await getHighlighterChildren({ 187 | searchWords: ['this'], 188 | textToHighlight: 'This is text' 189 | }) 190 | const matches = node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR) 191 | expect(matches.length).to.equal(1) 192 | expect(matches[0].textContent).to.equal('This') 193 | }) 194 | 195 | it('should use the :highlightClassName if specified', async () => { 196 | const node = await getHighlighterChildren({ 197 | searchWords: ['text'], 198 | textToHighlight: 'This is text' 199 | }) 200 | expect(node.querySelector('mark').className).to.contain(HIGHLIGHT_CLASS) 201 | }) 202 | 203 | it('should use the :highlightStyle if specified', async () => { 204 | const node = await getHighlighterChildren({ 205 | highlightStyle: { color: 'red' }, 206 | searchWords: ['text'], 207 | textToHighlight: 'This is text' 208 | }) 209 | expect(node.querySelector('mark').style.color).to.contain('red') 210 | }) 211 | 212 | it('should use the :unhighlightStyle if specified', async () => { 213 | const node = await getHighlighterChildren({ 214 | unhighlightStyle: { color: 'gray' }, 215 | searchWords: ['text'], 216 | textToHighlight: 'This is text' 217 | }) 218 | expect(node.querySelector('span').style.color).to.contain('gray') 219 | }) 220 | 221 | it('should match terms without accents against text with accents', async () => { 222 | const node = await getHighlighterChildren({ 223 | sanitize: latinize, 224 | searchWords: ['example'], 225 | textToHighlight: 'ỆᶍǍᶆṔƚÉ' 226 | }) 227 | const matches = node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR) 228 | expect(matches.length).to.equal(1) 229 | expect(matches[0].textContent).to.equal('ỆᶍǍᶆṔƚÉ') 230 | }) 231 | 232 | it('should use the :highlightTag if specified', async () => { 233 | const node = await getHighlighterChildren({ 234 | autoEscape: true, 235 | highlightTag: 'span', 236 | searchWords: ['text'], 237 | textToHighlight: 'This is text' 238 | }) 239 | const matches = node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR) 240 | expect(matches[0].tagName).to.equal('SPAN') 241 | }) 242 | 243 | it('should support class components via :highlightTag', async () => { 244 | class HighlightTag extends React.Component { 245 | render () { 246 | const { highlightIndex, ...rest } = this.props 247 | 248 | return ( 249 | 250 | ) 251 | } 252 | } 253 | 254 | const node = await getHighlighterChildren({ 255 | autoEscape: true, 256 | highlightTag: HighlightTag, 257 | searchWords: ['text'], 258 | textToHighlight: 'This is text' 259 | }) 260 | const matches = node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR) 261 | expect(matches[0].tagName).to.equal('SPAN') 262 | }) 263 | 264 | it('should support stateless functional components via :highlightTag', async () => { 265 | const HighlightTag = ({ highlightIndex, ...rest }) => ( 266 | 267 | ) 268 | 269 | const node = await getHighlighterChildren({ 270 | autoEscape: true, 271 | highlightTag: HighlightTag, 272 | searchWords: ['text'], 273 | textToHighlight: 'This is text' 274 | }) 275 | const matches = node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR) 276 | expect(matches[0].tagName).to.equal('SPAN') 277 | }) 278 | 279 | it('should apply activeClassName to the match specified by activeIndex', async () => { 280 | const activeClassName = 'active' 281 | const node = await getHighlighterChildren({ 282 | activeIndex: 1, 283 | activeClassName, 284 | searchWords: ['text'], 285 | textToHighlight: 'This is text which should have this text highlighted' 286 | }) 287 | const matches = node.querySelectorAll('mark') 288 | expect(matches[1].classList.contains(activeClassName)).to.equal(true) 289 | }) 290 | 291 | it('should apply activeStyle to the match specified by activeIndex', async () => { 292 | const activeStyle = { color: 'red' } 293 | const node = await getHighlighterChildren({ 294 | activeIndex: 1, 295 | activeStyle, 296 | searchWords: ['text'], 297 | textToHighlight: 'This is text which should have this text highlighted' 298 | }) 299 | const matches = node.querySelectorAll('mark') 300 | expect(matches[1].style.color).to.equal('red') 301 | }) 302 | 303 | it('should support caseSensitive search', async () => { 304 | const node = await getHighlighterChildren({ 305 | caseSensitive: true, 306 | searchWords: ['th'], 307 | textToHighlight: 'This the three time' 308 | }) 309 | const matches = node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR) 310 | expect(matches).to.have.length(2) 311 | expect(matches[0].textContent).to.equal('th') 312 | expect(matches[1].textContent).to.equal('th') 313 | }) 314 | 315 | it('should support custom findChunks prop function', async () => { 316 | const node = await getHighlighterChildren({ 317 | findChunks: () => ( 318 | [ 319 | { start: 0, end: 1 }, 320 | { start: 5, end: 7 } 321 | ] 322 | ), 323 | searchWords: ['xxx'], 324 | textToHighlight: 'This is text' 325 | }) 326 | const matches = node.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR) 327 | expect(matches).to.have.length(2) 328 | expect(matches[0].textContent).to.equal('T') 329 | expect(matches[1].textContent).to.equal('is') 330 | 331 | const node2 = await getHighlighterChildren({ 332 | findChunks: () => ( 333 | [] 334 | ), 335 | searchWords: ['This'], 336 | textToHighlight: 'This is text' 337 | }) 338 | const matches2 = node2.querySelectorAll(HIGHLIGHT_QUERY_SELECTOR) 339 | expect(matches2).to.have.length(0) 340 | }) 341 | 342 | it('should render chucks with the appropriate classes when case-insensitive', async () => { 343 | const node = await getHighlighterChildren({ 344 | searchWords: ['This', 'is', 'text'], 345 | textToHighlight: 'This is text', 346 | highlightClassName: { This: 'this', is: 'is', text: 'text' } 347 | }) 348 | const allMatches = node.querySelectorAll('mark') 349 | expect(allMatches).to.have.length(3) 350 | expect(allMatches[0].classList).to.contain('this') 351 | expect(allMatches[1].classList).to.contain('is') 352 | expect(allMatches[2].classList).to.contain('text') 353 | }) 354 | 355 | it('should render chucks with the appropriate classes when case-sensitive', async () => { 356 | const node = await getHighlighterChildren({ 357 | caseSensitive: true, 358 | searchWords: ['This', 'is', 'TEXT'], 359 | textToHighlight: 'This is TEXT', 360 | highlightClassName: { this: 'this', is: 'is', text: 'text' } 361 | }) 362 | const allMatches = node.querySelectorAll('mark') 363 | expect(allMatches).to.have.length(3) 364 | expect(allMatches[0].classList).not.to.contain('this') 365 | expect(allMatches[1].classList).to.contain('is') 366 | expect(allMatches[2].classList).not.to.contain('text') 367 | }) 368 | 369 | it('should spread additional custom props onto the wrapper span', async () => { 370 | const node = await getHighlighterChildren({ 371 | searchWords: ['This', 'is', 'TEXT'], 372 | textToHighlight: 'This is TEXT', 373 | 'data-test-attribute': 'data attribute content', 374 | title: 'span title', 375 | className: 'test-class' 376 | }) 377 | 378 | const matches = node.querySelectorAll('.test-class') 379 | expect(matches).to.have.length(0) 380 | expect(node.title).to.equal('span title') 381 | expect(node.classList.contains('test-class')).to.equal(true) 382 | expect(node.dataset.testAttribute).to.equal('data attribute content') 383 | }) 384 | 385 | it('should use :unhighlightTag if provided', async () => { 386 | const node = await getHighlighterChildren({ 387 | searchWords: ['This', 'is', 'TEXT'], 388 | textToHighlight: 'Hello World', 389 | unhighlightTag: 'div', 390 | unhighlightClassName: UNHIGHLIGHT_CLASS 391 | }) 392 | 393 | const matches = node.querySelectorAll(`.${UNHIGHLIGHT_CLASS}`) 394 | expect(matches).to.have.length(1) 395 | expect(matches[0].nodeName).to.equal('DIV') 396 | }) 397 | 398 | it('should support class components via :unhighlightTag', async () => { 399 | class UnHighlightTag extends React.Component { 400 | render () { 401 | const { highlightIndex, ...rest } = this.props 402 | 403 | return ( 404 | 405 | ) 406 | } 407 | } 408 | 409 | const node = await getHighlighterChildren({ 410 | autoEscape: true, 411 | unhighlightTag: UnHighlightTag, 412 | searchWords: ['text'], 413 | textToHighlight: 'This is text' 414 | }) 415 | const matches = node.querySelectorAll(UNHIGHLIGHT_QUERY_SELECTOR) 416 | expect(matches[0].tagName).to.equal('A') 417 | }) 418 | 419 | it('should support stateless functional components via :unhighlightTag', async () => { 420 | const UnHighlightTag = ({ highlightIndex, ...rest }) => ( 421 | 422 | ) 423 | 424 | const node = await getHighlighterChildren({ 425 | autoEscape: true, 426 | unhighlightTag: UnHighlightTag, 427 | searchWords: ['text'], 428 | textToHighlight: 'This is text' 429 | }) 430 | const matches = node.querySelectorAll(UNHIGHLIGHT_QUERY_SELECTOR) 431 | expect(matches[0].tagName).to.equal('A') 432 | }) 433 | }) 434 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | /** @flow */ 2 | import Highlighter from './Highlighter' 3 | 4 | export default Highlighter 5 | -------------------------------------------------------------------------------- /src/test-utils.js: -------------------------------------------------------------------------------- 1 | import { createRoot } from 'react-dom/client' 2 | 3 | /** 4 | * Helper method for testing components that may use Portal and thus require cleanup. 5 | * This helper method renders components to a transient node that is destroyed after the test completes. 6 | * Note that rendering twice within the same test method will update the same element (rather than recreate it). 7 | */ 8 | export function render (markup) { 9 | if (!render._root) { 10 | const div = document.createElement('div') 11 | document.body.appendChild(div) 12 | const root = createRoot(div) 13 | render._root = root 14 | render._mountNode = div 15 | 16 | afterEach(render.unmount) 17 | } 18 | 19 | render._root.render(markup) 20 | } 21 | 22 | /** 23 | * The render() method auto-unmounts components after each test has completed. 24 | * Use this method manually to test the componentWillUnmount() lifecycle method. 25 | */ 26 | render.unmount = function () { 27 | if (render._root) { 28 | render._root.unmount() 29 | document.body.removeChild(render._mountNode) 30 | render._root = null 31 | render._mountNode = null 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/tests.js: -------------------------------------------------------------------------------- 1 | // Reference: https://babeljs.io/docs/usage/polyfill/ 2 | // Reference: https://github.com/zloirock/core-js 3 | // Polyfill a full ES6 environment 4 | import 'babel/polyfill' 5 | 6 | // Reference: https://github.com/webpack/karma-webpack#alternative-usage 7 | const tests = require.context('.', true, /\.test\.js$/) 8 | tests.keys().forEach(tests) 9 | -------------------------------------------------------------------------------- /webpack.config.dev.js: -------------------------------------------------------------------------------- 1 | const HtmlWebpackPlugin = require('html-webpack-plugin') 2 | const path = require('path') 3 | const webpack = require('webpack') 4 | 5 | module.exports = { 6 | devtool: 'eval', 7 | entry: [ 8 | 'babel/polyfill', 9 | './website/index.js' 10 | ], 11 | output: { 12 | path: 'build', 13 | filename: '/static/[name].js' 14 | }, 15 | plugins: [ 16 | new HtmlWebpackPlugin({ 17 | filename: 'index.html', 18 | inject: true, 19 | template: './website/index.html' 20 | }), 21 | new webpack.NoErrorsPlugin() 22 | ], 23 | module: { 24 | loaders: [ 25 | { 26 | test: /\.js$/, 27 | loader: 'babel', 28 | exclude: path.join(__dirname, 'node_modules') 29 | }, 30 | { 31 | test: /\.css$/, 32 | loaders: ['style', 'css?modules&importLoaders=1', 'cssnext'], 33 | exclude: path.join(__dirname, 'node_modules') 34 | } 35 | ] 36 | }, 37 | devServer: { 38 | contentBase: 'build', 39 | port: 3567 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /webpack.config.dist.base.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | 3 | module.exports = { 4 | devtool: 'source-map', 5 | entry: [ 6 | './src/index.js' 7 | ], 8 | output: { 9 | path: 'dist', 10 | library: 'react-highlight-words' 11 | }, 12 | plugins: [ 13 | ], 14 | externals: { 15 | 'react': 'react' 16 | }, 17 | module: { 18 | loaders: [ 19 | { 20 | test: /\.js$/, 21 | loader: 'babel', 22 | exclude: /(node_modules)/, 23 | include: path.join(__dirname, 'src') 24 | }, 25 | { 26 | test: /\.css$/, 27 | loaders: ['style', 'css?modules&importLoaders=1', 'cssnext'], 28 | exclude: path.join(__dirname, 'node_modules') 29 | } 30 | ] 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /webpack.config.dist.cjs.js: -------------------------------------------------------------------------------- 1 | const baseDistConfig = require('./webpack.config.dist.base') 2 | const _ = require('lodash') 3 | 4 | const cjsDistConfig = { 5 | output: { 6 | filename: '[name].js', 7 | libraryTarget: 'commonjs2' 8 | } 9 | } 10 | 11 | module.exports = _.merge(baseDistConfig, cjsDistConfig) 12 | -------------------------------------------------------------------------------- /webpack.config.dist.umd.js: -------------------------------------------------------------------------------- 1 | const baseDistConfig = require('./webpack.config.dist.base') 2 | const _ = require('lodash') 3 | 4 | const umdDistConfig = { 5 | output: { 6 | filename: '[name].umd.js', 7 | libraryTarget: 'umd' 8 | } 9 | } 10 | 11 | module.exports = _.merge(baseDistConfig, umdDistConfig) 12 | -------------------------------------------------------------------------------- /webpack.config.test.js: -------------------------------------------------------------------------------- 1 | const HtmlWebpackPlugin = require('html-webpack-plugin') 2 | const path = require('path') 3 | const webpack = require('webpack') 4 | 5 | module.exports = { 6 | devtool: 'eval', 7 | entry: [ 8 | 'babel/polyfill', 9 | './website/index.js' 10 | ], 11 | output: { 12 | path: 'build', 13 | filename: '/static/[name].js' 14 | }, 15 | plugins: [ 16 | new HtmlWebpackPlugin({ 17 | filename: 'index.html', 18 | inject: true, 19 | template: './website/index.html' 20 | }), 21 | new webpack.NoErrorsPlugin(), 22 | new webpack.DefinePlugin({ 23 | 'process.env': { 24 | // to temporarily suppress "ReactDOM.render is no longer supported in React 18" warnings 25 | // should be removed after switching to createRoot 26 | 'NODE_ENV': JSON.stringify('production') 27 | } 28 | }) 29 | ], 30 | module: { 31 | loaders: [ 32 | { 33 | test: /\.js$/, 34 | loader: 'babel', 35 | exclude: path.join(__dirname, 'node_modules') 36 | }, 37 | { 38 | test: /\.css$/, 39 | loaders: ['style', 'css?modules&importLoaders=1', 'cssnext'], 40 | exclude: path.join(__dirname, 'node_modules') 41 | } 42 | ] 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /webpack.config.website.js: -------------------------------------------------------------------------------- 1 | const HtmlWebpackPlugin = require('html-webpack-plugin') 2 | const path = require('path') 3 | const webpack = require('webpack') 4 | 5 | module.exports = { 6 | devtool: 'source-map', 7 | entry: [ 8 | 'babel/polyfill', 9 | './website/index.js' 10 | ], 11 | output: { 12 | path: 'build', 13 | filename: 'static/[name].js' 14 | }, 15 | plugins: [ 16 | new HtmlWebpackPlugin({ 17 | filename: 'index.html', 18 | inject: true, 19 | template: './website/index.html' 20 | }), 21 | new webpack.DefinePlugin({ 22 | 'process.env': { 23 | 'NODE_ENV': JSON.stringify('production') 24 | } 25 | }) 26 | ], 27 | module: { 28 | loaders: [ 29 | { 30 | test: /\.js$/, 31 | loader: 'babel', 32 | exclude: path.join(__dirname, 'node_modules') 33 | }, 34 | { 35 | test: /\.css$/, 36 | loaders: ['style', 'css?modules&importLoaders=1', 'cssnext'], 37 | exclude: path.join(__dirname, 'node_modules') 38 | } 39 | ] 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /website/Application.css: -------------------------------------------------------------------------------- 1 | .headerRow { 2 | height: 300px; 3 | display: flex; 4 | align-items: flex-end; 5 | justify-content: center; 6 | background-color: #263238; 7 | } 8 | 9 | .logo { 10 | display: block; 11 | } 12 | 13 | .body { 14 | display: flex; 15 | justify-content: center; 16 | } 17 | 18 | .card { 19 | max-width: 600px; 20 | display: flex; 21 | flex-direction: column; 22 | padding: 15px 20px 20px; 23 | background-color: #eceff1; 24 | box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, .05); 25 | border-radius: .5em; 26 | margin: 1rem; 27 | } 28 | 29 | .footer { 30 | text-align: center; 31 | color: #37474f; 32 | font-size: .8em; 33 | } 34 | -------------------------------------------------------------------------------- /website/Application.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import HighlighterExample from '../src/Highlighter.example' 3 | import styles from './Application.css' 4 | 5 | export default function Application () { 6 | return ( 7 | 8 | 9 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | react-highlight-words is available under the MIT license. 23 | 24 | 25 | ) 26 | } 27 | -------------------------------------------------------------------------------- /website/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | background-color: #78909c; 4 | font-family: 'Roboto', 'Open Sans', sans-serif; 5 | font-size: 14px; 6 | } 7 | 8 | * { 9 | box-sizing: border-box; 10 | } 11 | -------------------------------------------------------------------------------- /website/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | react-highlight-words 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /website/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This is the entry point to the documentation/demo/test harness site for react-highlight-words. 3 | * This target is published to the root of the `gh-pages` branch. 4 | * @flow 5 | */ 6 | import Application from './Application' 7 | import React from 'react' 8 | import { createRoot } from 'react-dom/client' 9 | import './index.css' 10 | 11 | const root = createRoot(document.getElementById('root')) 12 | root.render() 13 | --------------------------------------------------------------------------------
89 | 90 | View the source 91 | 92 |