- Notifications
You must be signed in to change notification settings - Fork32
Simple and lightweight (< 2kB) HTML string to React element conversion library
License
pveyes/htmr
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Simple and lightweight (< 2kB) HTML string to react element conversion library
$ yarn add htmr# or$ npm install htmr --save
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 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});}
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-')]});
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.
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>;}
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.
- 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
insidep
element like<p><div>text</div></p>
- Script tag is not rendered using
dangerouslySetInnerHTML
by default due to security. You can opt in by usingdangerouslySetChildren
- Style tag renders it children using
dangerouslySetInnerHTML
by default. You can also reverse this behavior using same method.
HTML to react element:
HTML (page) to react component (file/string):
MIT
About
Simple and lightweight (< 2kB) HTML string to React element conversion library