• Stars
    star
    526
  • Rank 84,247 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

htmr Actions Status bundle size

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 htmr from 'htmr';

function HTMLComponent() {
  return htmr('<p>No more dangerouslySetInnerHTML</p>');
}

The API also accepts second argument options containing few optional fields. Below are their default values:

const options = {
  transform: {},
  preserveAttributes: [],
  dangerouslySetChildren: ['style'],
};
htmr(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 like styled-components.

import React from 'react';
import htmr from 'htmr';
import styled from 'styled-components';

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',
};

function TransformedHTMLComponent() {
  // will return <Paragraph><span>{'Custom component'}</span></Paragraph>
  return htmr('<p><a>Custom component</a></p>', { transform });
}

You can also provide default transform using underscore _ as property name.

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';

const transform = {
  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') {
      // use `key` because it's possible that <Text> is rendered
      // inside array as sibling
      return <Text key={node}>{node}</Text>;
    }

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

function NativeHTMLRenderer(props) {
  return htmr(props.html, { transform });
}

preserveAttributes

By default htmr will convert HTML attributes to camelCase 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

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

dangerouslySetChildren

By default htmr will only render children of style tag inside dangerouslySetInnerHTML due to security reason. You can override this behavior by passing array of HTML tags if you want the children of the tag to be rendered dangerously.

htmr(html, { dangerouslySetChildren: ['code', 'style'] });

Note that if you still want style tag to be rendered using dangerouslySetInnerHTML, you still need to include it in the array.

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 htmr from 'htmr';

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

function ComponentWithSibling() {
  // if using react 16, simply use the return value because
  // v16 can render array
  return htmr(html);
  // if using react 15 and below, wrap in another component
  return <div>{htmr(html)}</div>;
}

Use Cases

This library was initially built to provides easy component mapping between HTML string and React component. It's mainly used to render custom component from HTML string returned from an API. This library prioritize file size and simple API over full HTML conversion coverage and other features like JSX parsing or 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 dangerouslySetChildren
  • Style tag renders it children using dangerouslySetInnerHTML by default. You can also reverse this behavior using same method.

Related projects

HTML to react element:

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

License

MIT

More Repositories

1

naskah

Bahasa pemrograman dengan sintaks Bahasa Indonesia (Programming language with Indonesian syntax) 🇮🇩
Rust
158
star
2

use-less

React hooks that help you do what you already did, with more indirection
TypeScript
150
star
3

raw.macro

Read file contents at build time via babel-plugin-macros or SWC plugin.
JavaScript
149
star
4

katla

Indonesian version of Wordle
TypeScript
141
star
5

indihmm

Indihome real time twitter rant dashboard
TypeScript
69
star
6

aperture

Color theme for VSCode to help you focus
68
star
7

theme-in-css

Type-safe CSS custom properties (CSS variables) for theming purpose
TypeScript
65
star
8

vite-plugin-sloth

Fresh take on static site generation, using HTML-first approach to build website. Powered by ⚡️ Vite
HTML
44
star
9

oge

Page metadata as a service
HTML
26
star
10

atom-snazzy-clear-syntax

Modern, elegant, clean and consistent Atom syntax theme
CSS
13
star
11

asset-graph-webpack-plugin

Webpack plugin to easily get assets dependency graph based on entry point
JavaScript
13
star
12

smartass

Test your javascript knowledge
JavaScript
12
star
13

paper-editor

Medium editor clone, extracted from pveyes/paper
JavaScript
8
star
14

text-fragments

Text Fragments and Selection utilities
JavaScript
8
star
15

vcb

Multi-User, Multi-Room Video Streaming using WebRTC and Websocket
JavaScript
5
star
16

scarecrow

Tanifund scraper & notification service leveraging GitHub Actions Scheduling Workflow
JavaScript
5
star
17

octopub

GitHub public data as a service
Rust
4
star
18

makna

JavaScript
3
star
19

slack-robot-state

slack-robot plugin to enable state management
JavaScript
3
star
20

jest-multi-project-monorepo-coverage-bug

A small repro step for https://github.com/facebook/jest/issues/9323
JavaScript
2
star
21

imstore

Immutable in memory key-value store
JavaScript
2
star
22

pveyes

2
star
23

glg

Git log parser for easier analysis
JavaScript
1
star
24

byzantine

Istanbul json coverage parser
JavaScript
1
star
25

next.js-i18n-app-pages-hybrid

Reproduction case for routing issue in app/pages hybrid with i18n config
TypeScript
1
star
26

localhost

dotfiles, editor config, notes, and other development setup
Shell
1
star
27

talks

Tech talks & slides
JavaScript
1
star
28

next-swc-ssg-code-elimination

JavaScript
1
star