GithubHelp home page GithubHelp logo

bvaughn / react-highlight-words Goto Github PK

View Code? Open in Web Editor NEW
2.1K 21.0 171.0 3.3 MB

React component to highlight words within a larger body of text

Home Page: https://bvaughn.github.io/react-highlight-words/

License: MIT License

JavaScript 94.93% CSS 4.20% HTML 0.88%

react-highlight-words's Introduction

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 { createRoot } from "react-dom/client";
import Highlighter from "react-highlight-words";

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

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 or String Type of tag to wrap around highlighted matches. Defaults to mark but can also be a React component (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
unhighlightTag Node or String Type of tag applied to unhighlighted parts. Defaults to span but can also be a React component (class or functional)
* 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 react-highlight-words

License

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

react-highlight-words's People

Contributors

allegro-mpralat avatar bigappleinsider avatar bvaughn avatar cesarandreu avatar chollier avatar ioloie avatar jmera avatar jnachtigall avatar kaungmyatlwin avatar markwoon avatar nathanpower avatar pserwylo avatar richardbradley avatar ryanchadly avatar salguerooo avatar sergei-startsev avatar telmen avatar umireon avatar yeion7 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-highlight-words's Issues

Take className for unhighlighted text chunks as a prop

Currently there is no way to pass a custom className to the text chunks which aren't highlighted. My use case is that I have a highlight style with negative margins matching the padding as I want the background not to be flush with the glyph boundaries while also preventing reflow in a large collection as the highlight changes.
Unfortunately, without the ability to set a block formatting context so that z-index will work on the plain children of the component, the source order controls their stacking and text before the highlight in the reading direction is hidden by its background.

From what I can see in the source, it seems pretty easy to add, but I can't think of a good name for the prop.

What do you think?
Thanks!

Bracket error regexp

If textToHighlight have bracket, for example:
textToHighlight='Hi (friend)'

I have got error if i remove this bracket: textToHighlight='Hi (friend'

main.js:375 Uncaught SyntaxError: Invalid regular expression: /БАНК "ТАВРИЧЕСКИЙ" (ОАО/: Unterminated group

I think trouble in 'highlight-words-core' in function escapeRegExpFn

React 16 support

Is react 16 supported ? If yes, then could you please update the peerDependencies for package.json ?

Warning on proptypes when a regex is passed as searchWords item

Hi, how are you?
I'm having a warning message from proptype validation when I pass a regex as a proptype validation.

Warning: Failed prop type: Invalid prop searchWords[0]of type regexp supplied to Highlighter, expected string.

Anyway, with the regex, the component higlights the correct words, so its working well.

Could you add regex as a proptype (i think it would be React.PropTypes.object) so the warning is not displayed anymore?

Thank you

Unable to add props to wrapper span

Is there an existing way to add standard DOM attributes to the span wrapper such as title or data-*? It could be as simple as spreading any remaining props to the child so we could do the following:

        <Highlighter
          className="gameName"
          highlightClassName="highlightName"
          searchWords={searchValue}
          textToHighlight={content.gameName}
          title="Play Game"
          data-ext="test"
        />

Can't highlight in multiple colors

I am trying to use React-Highlight-Words to apply two different highlighting styles to words based on if they are "good words" (green highlighting) or "bad" (red highlighting). But from what I can tell, there is only one "searchWords" list you can pass for the Highlight component to apply styling too. How would I go about having two lists for different styling?

Error when using the provided example

My mistake - resolved by changing "searchWords" prop into an array

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

Should accept regular expression as element in searchWords array

Hi, thanks so much for this library. I try to pass [new RegExp(\b(${myVariable})\b, 'i')] to searchWords. It works fine but produces below warning:

Warning: Failed prop type: Invalid prop `searchWords[0]` of type `regexp` supplied to `Highlighter`, expected `string`.

Case sensitivity flag?

I could not find one in the docs. Is this something intentional, or could I add a pull request?

Unwanted bold style

Hi there, thank you for this component.

When using it, I was surprised to get a bold style for each highlighted piece of string. This bold style is due to the Highlighter.css Term class, transmitted by a class of random generated name. I don't need it and the only way to get rid off this default style is to pass an highlightStyle attribute for each call of the component, or to set a counter style with !important in my CSS, which is in either case not convenient.

quoted search is still being treated as regex

when I search for "Download (" I get the following error stack.

index.js:180 Uncaught SyntaxError: Invalid regular expression: /(/: Unterminated group
    at RegExp (<anonymous>)
    at http://localhost:1212/dist/renderer.dev.js:16512:18
    at Stack.reduce (native)
    at defaultFindChunks (http://localhost:1212/dist/renderer.dev.js:16505:5)
    at Object.values.reduce (http://localhost:1212/dist/renderer.dev.js:1475:64)
    at Array.reduce (native)
    at getBundleSearchResults (http://localhost:1212/dist/renderer.dev.js:1472:73)
    at Object.values.reduce (http://localhost:1212/dist/renderer.dev.js:1413:35)
    at Array.reduce (native)
    at getAllSearchResults (http://localhost:1212/dist/renderer.dev.js:1409:60)

Do I need to turn off regex entirely if user types in a quoted string?

Typing ".*" in crashes the demo

In general, it's pretty surprising that input is interpreted as a regex by default, so that "." highlights all characters. But it seems particularly bad that ".*" crashes the highlighter unless you specifically turn on autoEscape. This is reproducible at https://bvaughn.github.io/react-highlight-words/

I would consider defaulting autoEscape on, but I don't want to overprescribe a solution to the bug.

Special characters need to be escaped

Hi,
if i add the word 'Can.' as a searchword it marks 'Cano', 'Cana', 'Cann' ...
So the '.' is used as a wildcard
If u search for '.' everything gets marked
i think its wrong behaviour or you need at least a param to turn it off

How to run the tests?

I appreciate that most of this probably isn't your problem, but I was hoping you'd have some advice.

I am trying to run the tests for react-highlight-words, so that I can hack on #36 and #12

I can't run the tests on CentOS 7, as I am missing libSSL 1.0.0 and cannot install that version.

First attempt: Windows

First, I tried to install the project on Windows with npm install, but I get:

'NODE_ENV' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build:website: `npm run clean:website && NODE_ENV=production webpack --config webpack.config.website.js -p --bail`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build:website script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I think that the windows shell doesn't like commands like NODE_ENV=test karma start

Second attempt: CentOS 7

Never mind, I switched to a CentOS 7 VM and tried again.

Now I get:

$ npm install
....
$ npm test
...
09 11 2017 14:27:21.069:INFO [launcher]: Starting browser PhantomJS2
09 11 2017 14:27:21.082:ERROR [launcher]: Cannot start PhantomJS2
...
09 11 2017 14:27:21.219:ERROR [launcher]: PhantomJS2 failed 2 times (cannot start). Giving up.
npm ERR! Test failed.  See above for more details.

(with no diagnostic info, which is unhelpful).

So I tried to find out what's wrong with PhantomJS2:

$ find * -name phantomjs
node_modules/karma-phantomjs2-launcher/node_modules/phantomjs2-ext/bin/phantomjs
node_modules/karma-phantomjs2-launcher/node_modules/phantomjs2-ext/lib/phantom/bin/phantomjs
node_modules/karma-phantomjs2-launcher/node_modules/.bin/phantomjs
node_modules/phantomjs2/bin/phantomjs
node_modules/phantomjs2/lib/phantom/bin/phantomjs
node_modules/img-stats/test/phantomjs
node_modules/.bin/phantomjs
$ node_modules/karma-phantomjs2-launcher/node_modules/phantomjs2-ext/bin/phantomjs
/home/vagrant/react-highlight-words/node_modules/karma-phantomjs2-launcher/node_modules/phantomjs2-ext/lib/phantom/bin/phantomjs: error while loading shared l
ibraries: libssl.so.1.0.0: cannot open shared object file: No such file or directory

(This is after installing fontconfig, openssl and libssh)

I do have libssl, but not that version:

$ ls -l /usr/lib64/libssl*
-rwxr-xr-x. 1 root root 315072 May 30 15:31 /usr/lib64/libssl3.so
lrwxrwxrwx. 1 root root     16 Nov  9 14:20 /usr/lib64/libssl.so.10 -> libssl.so.1.0.2k
-rwxr-xr-x. 1 root root 470336 Aug  4 06:41 /usr/lib64/libssl.so.1.0.2k

According to https://www.centos.org/forums/viewtopic.php?t=60336 , it is not possible to install openssl 1.0.0 on a CentOS 7 box.

Do you know what O/S these tests will run on, or how to fix on CentOS 7?

Thanks,

Rich

Im just looking for help but was ignored

Don't know what's the problem with the owner of this library. If you cant help, you dont need to lock my issue. Someone might have help me instead but anyway thanks. That will not happen anymore.

Match accuracy settings are missing

Hello, thanks for the library.
In https://markjs.io/#mark there are few options how highlight should mark words - react-highlight-words works now in accuracy: "partially" mode only. Are there any plans to extend the settings in the near future? I am currently looking for the solution how to mark only exact match of words.

autoEscape=false not working

autoEscape: Escape characters in searchWords which are meaningful in regular expressions.
However, when input ‘***x’, the component crashes.

Highlight other component text

Hi There,

I am trying to add Highlighter to "react-json-view" object. But, I am not sure it is possible or not. If it is, how we do it, please?

for example import ReactJson from 'react-json-view'; <ReactJson name='Request' iconStyle='square' collapsed='2' theme='grayscale:inverted' src={this.props.Request} />

Thank you.

Support word boundaries

When I use the demo and search for the word and it finds and highlights b<mark ...>and</mark>s.

Would be great with an option to make it NOT match unless the words is limited by a word delimiter. E.g. match and highlight <mark>and</mark>erson and the full word <mark>and</mark>.

Highlighting shorter words first causes missed highlights.

Hi there, thanks for this component.

One issue I've noticed is that when you pass in a list of keywords, it doesn't highlight long keywords if a previous keyword which is a subset of the longer keyword is highlighted.

In your example page, take the phrase:

political bands which

If you search for "bands" then it highlights correctly as:

political bands which

However, if you search "and bands" then it highlights incorrectly as:

political bands which

This is likely caused by the HTML being changed to:

political b<span ...>and</span>s which

causing the subsequent search for "bands" to not find anything. I believe if you were to sort the list of keywords by length first, then longer keywords will always highlight first. In this situation, the result would first be highlighted as:

political <span ...>b<span...>and</span>s</span>

which, although results in nested spans, should work as desired.

Null `textToHighlight` causes exception

I have some properties which are nullable, which I want to highlight.
Currently, <Highlight> will throw an exception if textToHighlight is null, forcing me to do:

                                    <Highlighter
                                        searchWords={[this.state.nameFilterText]}
                                        autoEscape="true"
                                        textToHighlight={entity.name || ""}
                                    />

I think it would be slightly nicer (and robust) if the library accepted null input and produced null output (or "").

(Thanks for a great lib!)

Missing typescript typings

I'd like to work on this, but it would be helpful if the project included the type definitions for anyone who wants to include this in a project using typescript.

Unless you object, I will raise a PR within a day or two, ... or sooner 😃

Highlight only part of the match

I've a regex as the following:

`(\\b|_|-)${filter}`

So I want to find words inside a string, but if the word is "_foo" I like to match it also, while commonly word boundaries (\b) are not matching it.

The limit I find is i don't want to highlight the _ char.

I think I cant reach this by using the findChunks function, but it seems complex for a common task like this. So, I'm wondering if adding a prop like "highlightOnlyGroup" can be useful.

The idea is to being able to do something like:

`(?:\\b|_|-)(${filter})`

So, a non capturing group, which is ignored, and only the text inside the capturing group is used.

Future alternatives can be the named groups of ES2018, but probably we are not ready yet.

Add multiple styles to multiple strings

const text = "Hello Albert Good Morning"
<Highlighter
      highlightStyle={{ color: 'red' }}
      searchWords={["Hello", "Morning"]}
      textToHighlight={text}
/>

This line of code changes only the words "Hello" and "Morning" to a fontColor of red but i would also like to change the color of "Albert" and "Good" to blue at the same time. How can i achieve that?

This something i wanted to achieve

pic

react.PropTypes will be removed in V16

I noticed the following warning with a newer version of React which I installed today.

~/react-highlight-words/dist/main.js

Line: 90

Highlighter.propTypes = {
	  activeClassName: _react.PropTypes.string,
	  activeIndex: _react.PropTypes.string,
	  autoEscape: _react.PropTypes.bool,
	  highlightClassName: _react.PropTypes.string,
	  highlightTag: _react.PropTypes.string,
	  highlightStyle: _react.PropTypes.object,
	  searchWords: _react.PropTypes.arrayOf(_react.PropTypes.string).isRequired,
	  textToHighlight: _react.PropTypes.string.isRequired,
	  sanitize: _react.PropTypes.func
	};

Creates the following warning:
Warning: Accessing PropTypes via the main React package is deprecated, and will be removed in React v16.0. Use the latest available v15.* prop-types package from npm instead. For info on usage, compatibility, migration and more, see https://fb.me/prop-types-docs

Trying to match \b (word boundary) regex results in eternal loop and out-of-memory

I am using Highlighter in a project where only the beginning of words should be hightlighted. The code is like this:

<Highlighter
  // '\b' is a word boundary making sure we match only at the beginning of a word
  searchWords={`\\b${this.inputToHighlight}`}
  textToHighlight={'m'}
/>

If the ${this.inputToHighlight = '' (empty string) so that searchWords evaluates to \\b then this results in an loop and eventally an time-out or out-of-memory.

Other than in this edge case, it works to match word boundaries this way. I worked around the issue for now by using

    searchWords={this.inputToHighlight ? [`\\b${this.inputToHighlight}`] : ['']}

Stack-Trace (from Firefox Console, but time-out also happens in Chrome and IE) is like:

The above error occurred in the <Highlighter> component:
    in Highlighter (at SearchInput.js:140)
    in div (at SearchInput.js:138)
    in div (created by Option)
    in Option (created by Select)
    in div (created by Select)
    in div (created by Select)
    in div (created by Select)
    in Select (created by CreatableSelect)
    in CreatableSelect (created by Async)
    in Async (created by AsyncCreatableSelect)
    in AsyncCreatableSelect (at SearchInput.js:181)
    in form (at SearchInput.js:157)
    in SearchInput (at SearchApp.js:31)
    in div (at SearchApp.js:30)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://fb.me/react-error-boundaries to learn more about error boundaries.
react-dom.development.js:9747
Error: Script terminated by timeout at:
findChunks/<@webpack-internal:///540:373:14
findChunks@webpack-internal:///540:360:12
findAll@webpack-internal:///540:302:17
Highlighter@webpack-internal:///540:137:18
mountIndeterminateComponent@webpack-internal:///498:8032:15
beginWork@webpack-internal:///498:8221:16
performUnitOfWork@webpack-internal:///498:10224:16
workLoop@webpack-internal:///498:10288:26
callCallback@webpack-internal:///498:542:9
invokeGuardedCallbackDev@webpack-internal:///498:581:7
invokeGuardedCallback@webpack-internal:///498:438:5
renderRoot@webpack-internal:///498:10366:7
performWorkOnRoot@webpack-internal:///498:11014:24
performWork@webpack-internal:///498:10967:7
batchedUpdates@webpack-internal:///498:11086:9
batchedUpdates@webpack-internal:///498:2330:12
dispatchEvent@webpack-internal:///498:3421:5
EventListener.handleEvent*listen@webpack-internal:///500:29:7
trapBubbledEvent@webpack-internal:///498:3381:10
listenTo@webpack-internal:///498:3744:9
ensureListeningTo@webpack-internal:///498:13717:3
setInitialProperties$1@webpack-internal:///498:13956:7
finalizeInitialChildren@webpack-internal:///498:14989:5
completeWork@webpack-internal:///498:8648:19
completeUnitOfWork@webpack-internal:///498:10132:18
performUnitOfWork@webpack-internal:///498:10234:14
workLoop@webpack-internal:///498:10288:26
callCallback@webpack-internal:///498:542:9
invokeGuardedCallbackDev@webpack-internal:///498:581:7
invokeGuardedCallback@webpack-internal:///498:438:5
renderRoot@webpack-internal:///498:10366:7
performWorkOnRoot@webpack-internal:///498:11014:24
performWork@webpack-internal:///498:10967:7
requestWork@webpack-internal:///498:10878:7
scheduleWorkImpl@webpack-internal:///498:10732:11
scheduleWork@webpack-internal:///498:10689:12
scheduleTopLevelUpdate@webpack-internal:///498:11193:5
updateContainer@webpack-internal:///498:11231:7
renderSubtreeIntoContainer/<@webpack-internal:///498:15226:7
unbatchedUpdates@webpack-internal:///498:11102:12
renderSubtreeIntoContainer@webpack-internal:///498:15225:5
render@webpack-internal:///498:15290:12
SearchApp@webpack-internal:///496:51:3
@webpack-internal:///452:41:19
mightThrow@webpack-internal:///7:3534:21
setTimeout handler*resolve/<@webpack-internal:///7:3640:9
fire@webpack-internal:///7:3268:11
fireWith@webpack-internal:///7:3398:7
fire@webpack-internal:///7:3406:5
fire@webpack-internal:///7:3268:11
fireWith@webpack-internal:///7:3398:7
ready@webpack-internal:///7:3878:3
completed@webpack-internal:///7:3888:2
EventListener.handleEvent*@webpack-internal:///7:3904:2
@webpack-internal:///7:28:4
@webpack-internal:///7:14:3
@http://localhost/js/app.bundle.js:113:1
__webpack_require__@http://localhost/js/app.bundle.js:20:12
@webpack-internal:///452:2:65
@http://localhost/js/app.bundle.js:2927:1
__webpack_require__@http://localhost/js/app.bundle.js:20:12
@http://localhost/js/app.bundle.js:1635:18
__webpack_require__@http://localhost/js/app.bundle.js:20:12
@http://localhost/js/app.bundle.js:63:18
@http://localhost/js/app.bundle.js:1:11
app.bundle.js%20line%203510%20%3E%20eval:373:14
Error: Should have found an error boundary. This error is likely caused by a bug in React. Please file an issue.
app.bundle.js%20line%20789%20%3E%20eval:42:15
    invariant
    invariant.js:42
    renderRoot
    react-dom.development.js:10392
    performWorkOnRoot
    react-dom.development.js:11014
    performWork
    react-dom.development.js:10967
    batchedUpdates
    react-dom.development.js:11086
    batchedUpdates
    react-dom.development.js:2330
    dispatchEvent
    react-dom.development.js:3421
    dispatchEvent self-hosted:1035:17

I could setup something on glitch.com or codepen, but do not have much time at the moment, so hopefully this is enough to reproduce.

Highlight using cursor

Hi,

Great work on this.

I'm wondering if it's possible to highlight using the cursor, instead of searching the text manually. I'd imagine there would have to be a data store of sorts for it to store what you've highlighted persistently.

How might this be possible using your repo?

Thanks

Case-insensitivity only works if the searchword string is 1 character long

I'm having problems with the case-sensitivity.

It seems like the case-insensitivity only works if the searchword string is 1 character long.

For example, if I am highlighting text in the string "Prom", and my searchword string is "p", it works as expected, finds the "P" and highlights. But if the searchword string is "pr", it doesn locate the "Pr" in my original string.

Similarly, if I am highlighting text in the string "FRench", and my searchword string is "f", it find the "F" and highlights. But if the searchword string is "fr", it doesn locate the "FR" in my original string.

One last example with same string("FRench"): if my searchword string is "r", it find the "R". But if the searchword string is "re", it doesn locate the "Re" in my original string.

Keyboard AND Inline calendar

It it possible to display the inline calendar, as well as retain focus on the manual input? When I tab focus to an component I'm able to write, but the calendar doesn't appear and if I click on the input field the calendar is there, but I can no longer write in the field.

What I'd love to be able to do is have the calendar appear as an option for people, but retain manual keyboard entry possible (as that's the general expected way for people to enter their dates).

when trying to highlight a word starts with "(" - there's an error

hi.
thank for this lib :)

when using it, we encountered a situation where the word to be highlighted is: "(1 ".

<Highlighter searchWords={['(1 ']} textToHighlight={'hello'} />

and we got this error in console:
Uncaught SyntaxError: Invalid regular expression: /(1 /: Unterminated group
at new RegExp ()
at index.js:180
at Array.reduce ()
at defaultFindChunks (index.js:173)
at findAll (index.js:112)
at Highlighter (Highlighter.js:48)
at mountIndeterminateComponent (react-dom.development.js:8574)
at beginWork (react-dom.development.js:8978)
at performUnitOfWork (react-dom.development.js:11814)
at workLoop (react-dom.development.js:11843)

Contextual highlight classes

  • I had a requirement to highlight a few keywords in a sentence depending on their contexts, so a single highlightClassName was not sufficient. At the time i didn't have much time so i had it forked and published as an independent package here.

  • This is how it works.

Accept a prop contextualHighlightClasses which is an array of highlightClassName having one-two-one relation with words in searchWords and then apply the highlighClass accordingly.

  • Let me know if you guys are interested, I will sanitize the code and open a PR.

react dev mode warning in v0.15

#70 introduced a regression, which leads to a console warning:

Warning: React does not recognize the `highlightIndex` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `highlightindex` instead. If you accidentally passed it from a parent component, remove it from the DOM element.
    in mark (created by Highlighter)
    in span (created by Highlighter)
    in Highlighter (created by ...)
    in ...
    ...

Here's the code that produces the warning:

<Highlighter searchWords={[filterValue]} textToHighlight={name} autoEscape={true} />

The problem is that by default highlightTag is <mark> which does not support extra props:

highlightTag = 'mark',

<HighlightTag
className={highlightClassNames}
highlightIndex={highlightCount}
key={index}
style={highlightStyles}
>

/cc @pkmoran

Handling more complicated searchWord / matches scenarios (regex)

I have a few requirements that are hard to meet knowing:

  • Match only at the beginning of a word
    • Problem: js regex implementation of \b (word boundary) only works with ASCII chars, so is not really suitable for most real languages. Possible solution would be to use XRegExp (a wrapper around the native js RegExp), but this is not part of react-highlight-words. And I do not know if you wanna do the buy-in of adding XRegExp
  • I also need to highlight words after a hyphen, e.g. for searchWord=['Ma'] in Smith-Mayer the Ma should be highlighted. If it starts with -, but the - should not be part of match (not be highlighted).
    • Unfortunately, this is not possible with JS regex because it does not support look-behind and look-around regexes at all. Various other workarounds available on Stackoverflow, but they all require some JS fiddling....

So why am I writing this:

  • I think when it comes to real languages other than english or when the requirements are more complicated it is hard to use the lib as it is.

Also, I am not sure on how to proceed here :)

Looking into the source, my proposal would be to allow the findChunks function to be overridden as a prop (like there is sanitize already). Especially, all the above problem could be moved into the using app's domain if these lines could be overridden using a prop or similar:

https://github.com/bvaughn/highlight-words-core/blob/7cbba8346e08a68cbba77e7ef2c7df65f7dd1422/src/utils.js#L83-L89

I might try to send a PL, but not sure what direction to take considering the alternatives.

Include a activeHighlightIndex prop to the component

#I am trying to create something like the built in search of the chrome browser. You can notice that the first match will be orange while the rest of the matches are in yellow. We can now cycle through the matches by clicking next or previous button and this would update the background to orange for the active match.

I implemented this in my fork by doing something like this

let highlightCount = 0;
{chunks.map((chunk, index) => {
        const text = textToHighlight.substr(chunk.start, chunk.end - chunk.start)

        if (chunk.highlight) {
          highlightCount++;
          highlightClassName = classnames( highlightClassName , { active: highlightCount == activeHighlightIndex })
          return (
            <HighlightTag
              className={highlightClassName}
              key={index}
              style={highlightStyle}
            >
              {text}
            </HighlightTag>
          )
        } else {
          return (
            <span key={index}>{text}</span>
          )
        }
      })}

Allow markup in textToHighlight prop

I have a use case where I have a chat interface where each messages can contain markup like links.
I use this component to highlight search term within messages.

Right now markup is escaped and I modified the component to for my use case.

const output = chunks.map((chunk, index) => {
    const text = textToHighlight.substr(chunk.start, chunk.end - chunk.start)

    if (chunk.highlight) {
      let highlightClasses = classnames( highlightClassName , { 
        active: highlightCount == activeHighlightIndex 
      });
      highlightCount++;
      return (
         `<mark class="${highlightClasses}">${text}</mark>`
      )
    } else {
      return (
        `${text}`
      )
    }
  });
  return <span dangerouslySetInnerHTML={{__html: output.join('')}}></span>;

For this to work properly, I had to modify the highlight-words-core package to ignore markup while doing a search. Here is the separate issue for that.

It would be great if this feature could be included. I could work on a PR if you agree on this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.