@shanedaugherty/react-content-block

A react component for rendering html strings.

Usage no npm install needed!

<script type="module">
  import shanedaughertyReactContentBlock from 'https://cdn.skypack.dev/@shanedaugherty/react-content-block';
</script>

README

React Content Block

A react component for rendering html strings.

Simple Usage

import ContentBlock from '@shanedaugherty/react-content-block';

render() {
  return <ContentBlock html={'<div>Any html</div>'} />
}

With Configuration Example

This library exports a higher-order component that can be used to bind props at runtime.

ContentBlock.jsx

import { withConfiguration } from '@shanedaugherty/react-content-block';
import { CustomImageComponent, SyntaxHighlighter, Section } from '../components';

export default withConfiguration({
  getProps: (tagname, attributes, instanceData) => {
     switch(tagname) {
       case img: 
         return { srcset: instanceData.imageSizes.map(...) }
     }
  },
  replacements: {
    img: (props) => <CustomImageComponent {...props} />,
    code: (props) => <SyntaxHighlighter {...props} />,
    section: (props) => <Section {...props} />
  }
})

Page.jsx

import ContentBlock from './ContentBlock.jsx';

class Page extends React.Component {
  static state = { 
    html: null, 
    media: null 
  };
  
  async componentDidMount() {
    const page = await api.getPage('home');
    const { html, media } = page;
    this.setState({ html, media });
  }
  
  render() {
    const {html, media} = this.state;
    if (!html) return null;
    return (<ContentBlock html={html} data={media} />)
  }  
}

Props

replacements

Replacements can be passed to use custom components in place of any html tag.

getProps

A function that can be used to provide props to a custom component.

data

Instance data to be passed to the third parameter of getProps.

className

A classname to be applied to the wrapper div, can only be used when useWrapper is set to true. type: string default: ContentBlock

useWrapper

When true the content will be wrapped in a div. type: boolean default: false