Inspired by Sethorax/react-html-converter and aknuds1/html-to-react.
A React component that converts raw HTML to React components.
On the client, no additional dependencies are used beyond React. Cheerio is used for rendering static elements for server-side rendered applications.
This is useful for rending React components from a headless CMS in client side react applications.
yarn add raw-html-react
or
npm install raw-html-react
import React from 'react';
import ReactHtml from 'raw-html-react';
import MyComponent from '../components/MyComponent';
class Example extends React.Component {
render() {
const html = `<div data-react-component="MyComponent"></div>`;
return <ReactHtml html={html} componentMap={{ MyComponent }} />;
}
}
This component takes raw html as text and renders react components.
type ReactHtmlProps = {
html: String,
componentMap: Object,
componentAttribute?: String,
propsAttribute?: String,
contextWrapper?: React.Node,
onServerRender?: Function
};
Prop Name | Type | Required | Default Value | Description |
---|---|---|---|---|
html | String |
required |
HTML to be parsed and rendered with React components inline. | |
componentMap | Object |
required |
An object where the key is the value to be used in data-react-component attributes and the value is the reference to the actual react component. |
|
componentAttribute | Object |
optional | data-react-component | The react component to be rendered in place of the html element |
propsAttribute | Object |
optional | data-react-props | The props that will be passed to the react component. (JSON string) |
contextWrapper | Object |
optional | null | Wrapper component to be used when statically rendering for SSR. Typically a context provider. |
onServerRender | Function |
optional | null | A hook for modifying the server rendered html. A callback function that receives the cheerio root object ($) |
Sets the props that will be passed to the react component. (JSON format)
Constructor takes plain JSON object where the key is the value to be used in data-react-component
attributes and the value is the reference to the actual react component.