Simple and lightweight (< 2kB) HTML string to React element conversion library
Branch: master
Clone or download
greenkeeper and pveyes Update husky to the latest version 🚀 (#77)
## The devDependency [husky](https://github.com/typicode/husky) was updated from `0.14.3` to `1.0.0`.
This version is **not covered** by your **current version range**.

If you don’t accept this pull request, your project will work just like it did before. However, you might be missing out on a bunch of new features, fixes and/or performance improvements from the dependency update.

---

[Find out more about this release](https://github.com/typicode/husky).

<details>
  <summary>FAQ and help</summary>

  There is a collection of [frequently asked questions](https://greenkeeper.io/faq.html). If those don’t help, you can always [ask the humans behind Greenkeeper](https://github.com/greenkeeperio/greenkeeper/issues/new).
</details>

---


Your [Greenkeeper](https://greenkeeper.io) bot 🌴
Latest commit fbd834f Oct 2, 2018
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
flow-typed Add flowtype check (#3) Aug 14, 2017
src Add jest custom matcher (#73) Sep 9, 2018
.babelrc Add more attribute mapping (#2) Aug 13, 2017
.flowconfig Add flowtype check (#3) Aug 14, 2017
.gitignore
.prettierrc Use .prettierrc to unify config between different ext Jan 10, 2018
.travis.yml Greenkeeper yarn.lock support (#72) Sep 9, 2018
LICENSE Add LICENSE Sep 13, 2017
README.md
codecov.yml
package.json Update husky to the latest version 🚀 (#77) Oct 2, 2018
preprocessor.js Add more attribute mapping (#2) Aug 13, 2017
rollup.config.js remove es modules support for webpack Jan 26, 2018
yarn.lock

README.md

htmr Build Status bundle size codecov

Greenkeeper badge

Simple and lightweight (< 2kB) HTML string to react element conversion library

Install

$ yarn add htmr

# or

$ npm install htmr --save

Usage

Use the default export, and pass HTML string.

import React from 'react';
import convert from 'htmr';

class Component extends React.Component {
  render() {
    return convert('<p>No more dangerouslySetInnerHTML</p>');
  }
}

The API also accepts second argument options containing few optional fields:

const options = {
  transform: {},
  preserveAttributes: [],
};
convert(html, options);

transform

transform accepts key value pairs, that will be used to transforms node (key) to custom component (value). You can use it to render specific tag name with custom component. For example: component with predefined styles such as emotion / styled-components.

import React from 'react';
import convert from 'htmr';
import styled from 'emotion/react';

const Paragraph = styled('p')`
  font-family: Helvetica, Arial, sans-serif;
  line-height: 1.5;
`;

const transform = {
  p: Paragraph,
  // you can also pass string for native DOM node
  a: 'span',
};

class Component extends React.Component {
  render() {
    // will return <Paragraph><span>{'Custom component'}</span></Paragraph>
    return convert('<p><a>Custom component</a></p>', { transform });
  }
}

You can also provide default transform using underscore _ syntax, similar to pattern matching special fall-through case.

This can be useful if you want to do string preprocessing (like removing all whitespace), or rendering HTML as native view in react-native:

import React from 'react';
import { Text, View } from 'react-native';

let i = 0;

const transform = {
  // react-native uses View instead of div
  div: View,
  _: (node, props, children) => {
    // react-native can't render string without <Text> component
    // we can test text node by checking component props, text node won't have them
    if (typeof props === 'undefined') {
      // we use auto incrementing key because it's possible that <Text>
      // is rendered inside array as sibling
      return <Text key={i++}>{node}</Text>;
    }

    // render unknown tag using <View>
    // ideally you also filter valid props to <View />
    return <View {...props}>{children}</View>;
  },
};

class NativeHTMLRenderer extends React.Component {
  render() {
    return convert(this.props.html, { transform });
  }
}

preserveAttributes

By default htmr will convert attribute to camelCase version because that's what react uses. You can override this behavior by passing preserveAttributes options. Specify array of string / regular expression to test which attributes you want to preserve.

For example you want to make sure ng-if, v-if and v-for to be rendered as is

convert(html, { preserveAttributes: ['ng-if', new RegExp('v-')] });

Multiple children

You can also convert HTML string which contains multiple elements. This returns an array, so make sure to wrap the output inside other component such as div, or use React 16.

import React from 'react';
import convert from 'htmr';

const html = `
  <h1>This string</h1>
  <p>Contains multiple html tags</p>
  <p>as sibling</p>
`;

class Component extends React.Component {
  render() {
    // if using react 16, simply use the return value because
    // v16 can render array
    return convert(html);
    // if using react 15 and below, wrap in another component
    return <div>{convert(html)}</div>;
  }
}

Use Cases

This library was initially built to provides easy component mapping between HTML string and React component. It's mainly used in my blog to render custom component from HTML string returned from blog API. This library prioritize file size and simple API over full HTML conversion coverage and other features like flexible node traversal.

That's why I've decided to not implement some features (see Trade Off section below). If you feel like you need more features that's not possible using this library, you can check out some related projects below.

Trade Off

  • Inline event attributes (onclick="" etc) are not supported due to unnecessary complexity
  • htmr use native browser HTML parser when run in browser instead of using custom parser. Due to how browser HTML parser works, you can get weird result if you supply "invalid" html, for example div inside p element like <p><div>text</div></p>
  • Script tag is not rendered using dangerouslySetInnerHTML by default due to security. You can opt in by using custom component mapping
  • Style tag renders it children using dangerouslySetInnerHTML by default. You can also reverse this behavior using custom mapping.

Related projects

HTML to react element:

HTML (page) to react component (file/string):

License

MIT