Skip to content

shtrihstr/react-active-html

Folders and files

NameName
Last commit message
Last commit date

Latest commit

author
Oleksandr Strikha
Aug 3, 2018
26795ed · Aug 3, 2018

History

16 Commits
Mar 8, 2018
Mar 8, 2018
Mar 8, 2018
Mar 8, 2018
Mar 8, 2018
Aug 22, 2016
Mar 8, 2018
Mar 8, 2018
Aug 3, 2018
Aug 3, 2018

Repository files navigation

Build Status

Active HTML for ReactJS

Convert HTML string to React Components

Problem

The most of CMS provides content as pure html from WYSIWYG editors:

{
    "content": "<a href='/hello'>Hello World</a><img src='image.png' class='main-image' alt='' /><p>Lorem ipsum...</p>"
}

In this case you lose advantage of using React components in the content.

Solution

import activeHtml from 'react-active-html';

const componentsMap = {
    // replace <img> tags by custom react component
    img: props => <Image {...props} />,
    // replace <a> tags by React Router Link component
    a: props => <Link {...props} to={props.href} />,
    // add lazy load to all iframes
    iframe: props => (
        <LazyLoad>
            <iframe {...props} />
        </LazyLoad>
    )
};

class Html extends Component {
    shouldComponentUpdate(nextProps) {
        return this.props.content !== nextProps.content;
    }

    render() {
        // convert string property "content" to React components
        const nodes = activeHtml(this.props.content, componentsMap);
        return <div className="html">{nodes}</div>;
    }
}

Installation

Browser

npm install react-active-html

Node

npm install react-active-html xmldom
const activeHtml = require('react-active-html');
const xmldom = require('rxmldom');

activeHtml.DOMParser = new xmldom.DOMParser();