Giter Site home page Giter Site logo

react-highlighter's Introduction

npm version Build Status Coverage Status

react-highlighter

Highlight select fragments of a string using an HTML element and/or a class.

Installation

npm install react-highlighter --save

Usage

var Highlight = require('react-highlighter');

<Highlight search="brown">The quick brown fox jumps over the lazy dog</Highlight>

Props

  • search: The string of text (or Regular Expression) to highlight
  • caseSensitive: Determine whether string matching should be case-sensitive. Not applicable to regular expression searches. Defaults to false
  • ignoreDiacritics: Determine whether string matching should ignore diacritics. Defaults to false
  • diacriticsBlacklist: These chars are treated like characters that don't have any diacritics. Not applicable ignoreDiacritics is false. Defaults to none
  • matchElement: HTML tag name to wrap around highlighted text. Defaults to mark
  • matchClass: HTML class to wrap around highlighted text. Defaults to highlight
  • matchStyle: Custom style for the match element around highlighted text.

Development

Testing

Using Mocha/Chai/React.addons.TestUtils for testing.

npm test

Code Coverage

Generate a report using Istanbul to make sure your tests are touching everything! FYI, Travis will fail the build if there isn't at least 90% of statement coverage and 100% function coverage.

npm run coverage

Coveralls.io integration requires that the environment variable COVERALLS_REPO_TOKEN is set.

react-highlighter's People

Contributors

admmasters avatar bvaughn avatar cesarandreu avatar charliecochran avatar colindekker avatar ericgio avatar helior avatar hosmelq avatar kachkaev avatar llyys avatar mlunoe avatar nitzperetz avatar pasieronen avatar ultrafez 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

react-highlighter's Issues

Throws when search contains '\'

Hi, I send string values into search prop, but it throws (e.g. Uncaught SyntaxError: Invalid regular expression: /hello wor\/: \ at end of pattern) when the user enters backslash ''.

What would be the correct way of handling this, inside or outside of the component?

The 'search' property should accept 'null' or 'undefined' value

When there is nothing to search, the 'search' property of the component should accept null or undefined value to signify that nothing should be searched and the component should return the child 'as is'.

Currently, React throws

Warning: Failed prop type: The prop `search` is marked as required in `Highlighter`, but its value is `null`.
warning.js:33
    in Highlighter

when null is passed to the 'search' prop.

Add support for regex with global flag.

Regular expressions with a global flag are not working right. The code uses regex.test() and regex.exec(), both increasing an internal lastIndex counter.

For example:

<Highlight search=/brown|jumps/g">The quick brown fox jumps over the lazy dog</Highlight>

will only highlight 'jumps' because the first conditional search.test(remainingCleaned) will move the lastIndex counter right after the 'brown' keyword. search.exec(subject) will then only find 'jumps'.

Extract out search logic into a separate export

I'd be extremely helpful to extract out the search logic into a separate export that can be used outside JSX code.

Problem

I have a text toggle component that shows/hides text. I also have a search box that can search for text. If I haven't toggled the text component and I search I still want to know the number of hits that a search would highlight. I can't easily do this now without duplicating logic between this component and my search component.

Solution

If we extract out the search logic into a separate export, I could generate my RE, do the search, get the number of hits, then when I toggle the text view, render Highlight with the same RE and I should have the same number of hits as I do highlights.

Request missing from package.json

npm test with fresh checkout:

Error: Cannot find module 'request'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
...

Integrate w/ Github Releases

Use npm run dist to generate packaged distribution files (including minified variants) and publish those as Github Releases.

Deprecation warning for React.DOM.span

I'm using https://github.com/ericgio/react-bootstrap-typeahead which depends on your module. Since I added it, I noticed a deprecation warning which I could track down to react-highlighter:

Warning: Accessing factories like React.DOM.span has been deprecated and will be removed in v16.0+. Use the react-dom-factories package instead. Version 1.0 provides a drop-in replacement. For more info, see https://fb.me/react-dom-factories

This is caused by this line:

return React.DOM.span({'key': this.count}, string);

Would be great if this could be fixed. Thanks and keep up the good work!

[PropTypes] Allow React components for matchElement

Hi @helior and many thanks for your library! With react-highlighter I got from zero to all done in just 10 minutes, which is mind-blowing even in the React world!

I'm writing to share a minor issue I've faced when using <Highlight /> together with styled-components. Here's my code:

import styled from "styled-components";

const HighlightMark = styled.span`
  background: rgba(255, 255, 0, 0.3);
  border-radius: 4px;
  display: inline-block;
  margin: auto -3px;
  padding: 0 3px;
`;

// ... 

<Highlight search={highlightRegexp || false} matchElement={HighlightMark}>
  {text}
</Highlight>

This produces a warning in development environment:

Warning: Failed prop type: Invalid prop `matchElement` of type `function` supplied to `Highlighter`, expected `string`.

It'd be great if matchElement in PropTypes allowed using custom react components in addition to strings. The issue is only with the warning – all working great apart from that 🎉

Suppress new React deprecation warnings

React will be removing createClass and PropTypes in React 16.

image

"Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead."

"Warning: Highlighter: React.createClass is deprecated and will be removed in version 16. Use plain JavaScript classes instead. If you're not yet ready to migrate, create-react-class is available on npm as a drop-in replacement."

onClick handler not fired on children

<Link to='/home' onClick={this.onItemClick}>
  <i className="fa fa-file"></i>   
  <span id='works'>Click me - I work!!</span>
  <Highlighter search={this.props.query} caseSensitive={false}>
    {this.props.name}
  </Highlighter>
</Link>

this.onItemClick is only invoked when clicking on span#works. However, clicking any of the elements from Highlighter doesn't actually propagate the event in any way. I've found that it does work when I remove {'key': this.count} from the children in the array.

Highlighter Crashes on Numeric Values

Summary

Wrapping a numeric value in a Highlight component utilizing the search property has the potential to cause a TypeError.

image

Expected Behavior

The Highlighter should show the matching string within the return results. Here is an example of this working as expected with the search term of "test".

image

How to Replicate

Using the first image as an example, if the value of cell is numeric (ex. 1234 instead of "1234"), and the value of query is a partial match (ex. 123), the component breaks, citing the following:

image

Workaround

A workaround for this issue is to either call the toString() method or wrap the value in a String constructor.

Cannot apply unknown props to html elements.

In React 15.1.0 I am getting this warning in the console:

Warning: Unknown props search, caseSensitive, matchElement, matchClass, matchStyle on <span> tag. Remove these props from the element. For details, see https://fb.me/react-unknown-prop

This occurs from applying non standard props to an HTML element. i.e. <span search='string'>.

Thanks for your work on this project. 🙇

Issue when search starts or ends with whitespace

Due to the way React deals with whitespace in span, sometimes results can be a bit janky:

<Highlight search='s '>This is my test</Highlight>

Expected result: This is my test
Actual result: Thisismy test

I guess because React is doing:

<span>Thi</span>
<span>s </span>
<span>i</span>
<span>s </span>
<span>my test</span>

and ignores the whitespace inside <span>s </span> because it isn't part of a string.

Mismatches boundaries \b and ^

Although 'abc'.match(/\b\w/) equals ['a'] in JavaScript, react-highlighter acts as if it equals ['a', 'b', 'c'] instead. That is, the JSX element

<Highlight search={/\b\w/}>
  abc
</Highlight>

renders as abc instead of abc. (To verify that individual letters are being matched, rather than the entire string of all three letters, alter the matchClass prop so that it draws a border around matches instead of emboldening them.) Strangely, no problems arise with the expressions /\w\b/ and /\b\w\b/.

A similar problem occurs with anchors: substituting /^\w/ for /\b\w/ in the JSX element displayed above renders abc instead of abc, whereas /\w$/ and /^\w$/ behave as expected.

React-Native compatibility?

Would be nice to make this compatible with React-Native, removing all references of HTML to let the freedom to use React-Native components instead html.

Regular Expression

Thanks for sharing your component.

Would be useful if your component would accepts regular expression.

Feature request: multiple terms with different marks?

sooo ... an alternate syntax that goes something like this :

let searchMarks = {[
  {search:"abc", matchElement: "markOrange"},
  {search:"def", matchElement: "markBlue"},
  {search:"ghi", matchElement: "markYellow"},
]}

<Highlight searchMarks={searchMarks}>{sometext}</Highlight>

The requirement is to be able to use multiple search terms and define a separate highlight for each so different highlight colours can be used for each term.

I did have a go at nesting a Highlight tag with in itself (but with a different search and mark) but only the inner most Highlight seems to get executed.

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.