All Projects → pveyes → Htmr

pveyes / Htmr

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

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Htmr

picamera-motion
Raspberry Pi python PiCamera Lightweight Motion Detection. Includes easy curl script install/upgrade, whiptail admin menu system, single file web server and Rclone for uploading to a variety of web storage services.
Stars: ✭ 80 (-62.62%)
Mutual labels:  lightweight, simple
Meriyah
A 100% compliant, self-hosted javascript parser - https://meriyah.github.io/meriyah
Stars: ✭ 690 (+222.43%)
Mutual labels:  parser, jsx
Length.js
📏 JavaScript library for length units conversion.
Stars: ✭ 292 (+36.45%)
Mutual labels:  parser, converter
tb-grid
tb-grid is a super simple and lightweight 12 column responsive grid system utilizing css grid.
Stars: ✭ 19 (-91.12%)
Mutual labels:  lightweight, simple
To Milliseconds
Convert an object of time properties to milliseconds: `{seconds: 2}` → `2000`
Stars: ✭ 136 (-36.45%)
Mutual labels:  parser, converter
MatrixLib
Lightweight header-only matrix library (C++) for numerical optimization and machine learning. Contact me if there is an exciting opportunity.
Stars: ✭ 35 (-83.64%)
Mutual labels:  lightweight, simple
Qview
Practical and minimal image viewer
Stars: ✭ 460 (+114.95%)
Mutual labels:  lightweight, simple
CalDOM
An agnostic, reactive & minimalist (3kb) JavaScript UI library with direct access to native DOM.
Stars: ✭ 176 (-17.76%)
Mutual labels:  lightweight, simple
Html2pug
Converts HTML to Pug 🐶
Stars: ✭ 118 (-44.86%)
Mutual labels:  parser, converter
Sax Wasm
The first streamable, fixed memory XML, HTML, and JSX parser for WebAssembly.
Stars: ✭ 89 (-58.41%)
Mutual labels:  parser, jsx
cli
a lightweight and simple cli package
Stars: ✭ 12 (-94.39%)
Mutual labels:  lightweight, simple
Gelatin
Transform text files to XML, JSON, or YAML
Stars: ✭ 150 (-29.91%)
Mutual labels:  parser, converter
Hexo-Theme-MengD
A simple, lightweight Hexo theme(支持:pjax、discuss、twikoo、waline、valine评论)
Stars: ✭ 69 (-67.76%)
Mutual labels:  lightweight, simple
currency-converter
💰 Easily convert between 32 currencies
Stars: ✭ 16 (-92.52%)
Mutual labels:  converter, jsx
logger
☠ 😈 👀 Simple,Secure & Undetected (6.11.2017) keylogger for Windows :)
Stars: ✭ 37 (-82.71%)
Mutual labels:  lightweight, simple
Wondercms
WonderCMS - fast and small flat file CMS (5 files)
Stars: ✭ 330 (+54.21%)
Mutual labels:  lightweight, simple
ytmous
Anonymous Youtube Proxy
Stars: ✭ 60 (-71.96%)
Mutual labels:  lightweight, simple
jpopup
Simple lightweight (<2kB) javascript popup modal plugin
Stars: ✭ 27 (-87.38%)
Mutual labels:  lightweight, simple
Graphql Mst
Convert GraphQL to mobx-state-tree models
Stars: ✭ 22 (-89.72%)
Mutual labels:  parser, converter
Prance
Resolving Swagger/OpenAPI 2.0 and 3.0 Parser
Stars: ✭ 133 (-37.85%)
Mutual labels:  parser, converter

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

let i = 0;

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

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

Typescript, htmr transform and Web Components

If you're using htmr to transform custom elements in a typescript code, you'll get type error because custom element is not defined as valid property. To work around this, you can define the mapping in a separate object, and typecast as any while spreading in transform object:

import { ElementType } from 'react';
import { HtmrOptions } from 'htmr';

const customElementTransform: Record<string, ElementType> = {
  'virtual-scroller': VirtualScroller,
};

const options: HtmrOptions = {
  transform: {
    a: Anchor,
    ...(customElementTransform as any),
  },
};

htmr(html, options);

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].