0.0.15 • Published 4 years ago

string-to-react-element v0.0.15

Weekly downloads
22
License
MIT
Repository
github
Last release
4 years ago

string-to-react-element

How does it work?

You can pass a text and a an array containing objects that each contains a regex and a renderer function. This module replaces matched words in main text with your renderer function.The result is depended on your regexes .

installation

npm install --save string-to-react-element

example

import React from 'react';
import parser from 'string-to-react-element'
import { Link } from 'path/to/Link.jsx'

const urlRegex = /(https?:\/\/[^\s]+)|(http?:\/\/[^\s]+)/;
const mentionRegex = /(\s)([@][\w_-]+)|((^())[@][\w_-]+)/;
const hashtagRegex = /(\s)([#][\w_-]+)|((^())[#][\w_-]+)/;
const whiteSpaceRegex = /(\s)/;

const App =() => {
  const text = '#hello string-to-react-element@zamin4life @zamin4life';
  const renderer = [
      {
        regex: mentionRegex,
        renderer: splitItem => (
          <Link>
            {splitItem}
          </Link>
        ),
      },
      {
        regex: hashtagRegex,
        renderer: splitItem => (
          <Link>
            {splitItem}
          </Link>
        ),
      },
      {
        regex: urlRegex,
        renderer: splitItem => (
          <Link href={splitItem}>
            {splitItem}
          </Link>
        ),
      },
      {
        regex: whiteSpaceRegex,
        renderer: splitItem => (
          splitItem.split('').map((item) => {
            if (item === '\n') {
              return <br />;
            }
            if (item === ' ') {
              return <span> </span>;
            }
            if (item === '\t') {
              return <span>   </span>;
            }
            return item;
          })
        ),
      },
    ]
    return parser(text, renderer);
}

export default App;
0.0.14

4 years ago

0.0.15

4 years ago

0.0.13

4 years ago

0.0.11

4 years ago

0.0.12

4 years ago

0.0.10

4 years ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.3

4 years ago

0.0.5

4 years ago

0.0.2

4 years ago

0.0.1

4 years ago

1.2.2

4 years ago

1.2.1

4 years ago

1.2.0

4 years ago

1.1.2

4 years ago

1.1.1

4 years ago

1.0.2

4 years ago

0.1.1

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago