0.0.1 • Published 1 year ago

react-dynamic-highlighter v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

React Dynamic Highlighter

A react component for highlight words, supports custom className, tagName and other attributes.

demo: http://highlighter.meiling.fun/

Installation

$ npm install --save react-dynamic-highlighter

Usage

simple

import React from 'react';
const App = () => {
  return (
    <div>
      <Highlighter
        rules={[
          {
            word: ['stay'],
            caseSensitive: false,
            className: 'search-word-highlight',
          },
        ]}
      >
        Stay hungry, stay foolish
      </Highlighter>
    </div>
  );
};
.search-word-highlight {
  background-color: aquamarine;
}

custom React children

<Highlighter
  rules={[
    {
      word: ['warning', 'WARNING', 'Warning'],
      className: 'log-display-warning',
    },
    {
      regexp: /err(or)?/gi,
      className: 'log-display-error',
    },
    {
      regexp: /(http(s){0,1}:\/\/)([\S]+)/gi,
      tagName: 'a',
      className: 'log-link',
      getAttributes: (text) => ({
        href: text,
        target: '__blank',
        rel: 'noopener noreferrer',
      }),
    },
  ]}
>
  <pre className="log-display-container">
    <code>{logData}</code>
  </pre>
</Highlighter>
.log-display-container {
  width: 600px;
  padding: 16px;
  color: #c6c6c6;
  white-space: pre-wrap;
  word-break: break-all;
  background: #1e1e1e;
}

.log-display-warning {
  color: #fdbd72;
}

.log-display-error {
  color: #ff4b79;
}

Props

PropertyTypeRequiiredDescription
childrenReactNodetrueAny React Node
ruleHighlightRule[]trueDescribe how to highlight the words
onHighlightChange(count: Record<string, number>) => void;falseA function called when highlighting count changing

HighlightRule

PropertyTypeRequiiredDescription
regexpRegExpfalseA regexp to match highlighting words
wordstring[]falseThe highlighting words
caseSensitivebooleanfalseCase sensitivity. The default value is false
classNamestringtrueThe className will be added the highlighting node
tagNamestringfalseThe highlighting node Html TagName. The default value is span
getAttributes(text: string) => anyfalseSetting highlighting node with highlighting content
0.0.1

1 year ago