Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

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

License

NotificationsYou must be signed in to change notification settings

pveyes/htmr

Repository files navigation

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.

importReactfrom'react';importhtmrfrom'htmr';functionHTMLComponent(){returnhtmr('<p>No more dangerouslySetInnerHTML</p>');}

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

constoptions={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 withpredefined styles likestyled-components.

importReactfrom'react';importhtmrfrom'htmr';importstyledfrom'styled-components';constParagraph=styled.p`  font-family: Helvetica, Arial, sans-serif;  line-height: 1.5;`;consttransform={p:Paragraph,// you can also pass string for native DOM nodea:'span',};functionTransformedHTMLComponent(){// will return <Paragraph><span>{'Custom component'}</span></Paragraph>returnhtmr('<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 inreact-native:

importReactfrom'react';import{Text,View}from'react-native';consttransform={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 themif(typeofprops==='undefined'){// use `key` because it's possible that <Text> is rendered// inside array as siblingreturn<Textkey={node}>{node}</Text>;}// render unknown tag using <View>// ideally you also filter valid props to <View />return<View{...props}>{children}</View>;},};functionNativeHTMLRenderer(props){returnhtmr(props.html,{ transform});}

preserveAttributes

By defaulthtmr will convert HTML attributes to camelCase because that's what React uses. You can override this behavior by passingpreserveAttributes options. Specify array of string / regular expression to test which attributes you want to preserve.

For example you want to make sureng-if,v-if andv-for to be rendered as is

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

dangerouslySetChildren

By defaulthtmr will only render children ofstyle tag insidedangerouslySetInnerHTML 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 wantstyle tag to be rendered usingdangerouslySetInnerHTML, you still need to include it in the array.

Multiple children

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

importReactfrom'react';importhtmrfrom'htmr';consthtml=`  <h1>This string</h1>  <p>Contains multiple html tags</p>  <p>as sibling</p>`;functionComponentWithSibling(){// if using react 16, simply use the return value because// v16 can render arrayreturnhtmr(html);// if using react 15 and below, wrap in another componentreturn<div>{htmr(html)}</div>;}

Use Cases

This library was initially built to provides easy component mapping between HTMLstring and React component. It's mainly used to render customcomponent from HTML string returned from an API. This libraryprioritizefile size and simple API over full HTML conversion coverage and other featureslike JSX parsing or flexible node traversal.

That's why I've decided to not implement some features (seeTrade Offsection below). If you feel like you need more features that's not possibleusing 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 examplediv insidep element like<p><div>text</div></p>
  • Script tag is not rendered usingdangerouslySetInnerHTML by default due to security. You can opt in by usingdangerouslySetChildren
  • Style tag renders it children usingdangerouslySetInnerHTML 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


[8]ページ先頭

©2009-2025 Movatter.jp