Skip to content

Commit

Permalink
Merge pull request #27 from remarkablemark/chore-readme
Browse files Browse the repository at this point in the history
Tidy README instructions and examples
  • Loading branch information
remarkablemark authored Sep 28, 2016
2 parents cfffc97 + b89ca5b commit c7bfd40
Showing 1 changed file with 109 additions and 117 deletions.
226 changes: 109 additions & 117 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,22 @@
[![Coverage Status](https://coveralls.io/repos/github/remarkablemark/html-react-parser/badge.svg?branch=master)](https://coveralls.io/github/remarkablemark/html-react-parser?branch=master)
[![Dependency status](https://david-dm.org/remarkablemark/html-react-parser.svg)](https://david-dm.org/remarkablemark/html-react-parser)

An HTML to React parser.
An HTML to React parser:

```
Parser(htmlString[, options])
```

The parser converts an HTML string to [React element(s)](https://facebook.github.io/react/docs/glossary.html#react-elements). You can also `replace` element(s) with your own custom React element(s) via the parser options.
The parser converts a string of HTML to [React Element(s)](https://facebook.github.io/react/docs/glossary.html#react-elements).

### Example
There is also an option to [replace](#replacedomnode) element(s) with your own React Element(s) via the [parser options](#options).

#### Example

```js
var Parser = require('html-react-parser');
var reactElement = (
Parser('<p>Hello, world!</p>') // same as `React.createElement('p', {}, 'Hello, world!')`
);
require('react-dom').render(reactElement, document.getElementById('root'));
Parser('<p>Hello, world!</p>');
// same output as `React.createElement('p', {}, 'Hello, world!')`
```

## Installation
Expand All @@ -31,36 +31,70 @@ require('react-dom').render(reactElement, document.getElementById('root'));
$ npm install html-react-parser
```

Or you can download the script from a CDN:

```html
<!-- HTMLReactParser depends on React -->
<script src="https://unpkg.com/react@latest/dist/react.min.js"></script>
<script src="https://unpkg.com/html-react-parser@latest/dist/html-react-parser.min.js"></script>
```

See more [examples](https://github.com/remarkablemark/html-react-parser/tree/master/examples).

## Usage

Render to DOM:
Given that you have the following required:

```js
var Parser = require('html-react-parser');
var ReactDOM = require('react-dom');
// ES6
import Parser from 'html-react-parser';
import { render } from 'react-dom';
```

You may render one element:

// single element
ReactDOM.render(
```js
render(
Parser('<p>single</p>'),
document.getElementById('root')
);
```

// adjacent elements
ReactDOM.render(
You may render adjacent elements:

```js
// with JSX
render(
// the parser returns an array for adjacent elements
// so make sure they are nested under a parent React element
React.createElement('div', {}, Parser('<p>one</p><p>two</p>'))
<div>
{Parser('<p>brother</p><p>sister</p>')}
</div>,
document.getElementById('root')
);

// without JSX
render(
React.createElement('div', {},
Parser('<p>brother</p><p>sister</p>')
),
document.getElementById('root')
);
```

You may render nested elements:

// nested elements
ReactDOM.render(
```js
render(
Parser('<ul><li>inside</li></ul>'),
document.getElementById('root')
);
```

The parser will also preserve attributes:

// attributes are preserved
ReactDOM.render(
```js
render(
Parser('<section id="foo" class="bar baz" data-qux="42">look at me now</section>'),
document.getElementById('root')
);
Expand All @@ -70,122 +104,80 @@ ReactDOM.render(

#### replace(domNode)

The `replace` method allows you to swap an element with your own React element.

The first argument is `domNode`, which is an object which shares the same schema as the output from [htmlparser2.parseDOM](https://github.com/fb55/domhandler#example).
The `replace` method allows you to swap an element with your own React Element.

```js
Parser('<p id="replace">text</p>', {
replace: function(domNode) {
console.log(domNode);
// { type: 'tag',
// name: 'p',
// attribs: { id: 'replace' },
// children: [],
// next: null,
// prev: null,
// parent: null }

return;
// element is not replaced because
// a valid React element is not returned
}
});
```
The first argument is `domNode`, which is an object that has the same output as [htmlparser2.parseDOM](https://github.com/fb55/domhandler#example).

Simple example:
The element is only replaced if a valid React Element is returned.

```js
var Parser = require('html-react-parser');
var React = require('react');

var html = (
'<div>' +
'<p id="replace">'
'replace me' +
'</p>' +
'</div>'
);

var reactElement = Parser(html, {
replace: function(domNode) {
// with JSX
Parser('<p id="replace">text</p>', {
replace: (domNode) => {
if (domNode.attribs && domNode.attribs.id === 'replace') {
return React.createElement('span', {
style: { fontSize: '42px' }
}, 'replaced!');
// equivalent jsx syntax:
// return <span style={{ fontSize: '42px' }}>replaced!</span>;
return <span>replaced</span>;
}
}
});

require('react-dom').render(
reactElement,
document.getElementById('root')
);
// <div>
// <span style="font-size: 42px;">
// replaced!
// </span>
// </div>
```

Advanced example (the replaced element's children are kept):
Advanced example (keep the replaced children):

```js
var Parser = require('html-react-parser');
var React = require('react');

// used for recursively parsing DOM created from the HTML
var domToReact = require('html-react-parser/lib/dom-to-react');

var html = (
'<div>' +
'<p id="main">' +
'<span class="prettify">' +
'keep me and make me pretty!' +
'</span>' +
'</p>' +
'</div>'
);

var parserConfig = {
replace: function(domNode) {
var parsedChildren;
if (domNode.attribs) {
if (domNode.attribs.id === 'main') {
// continue parsing domNode's children with same config
parsedChildren = domToReact(domNode.children, parserConfig);
return React.createElement('span', {
style: { fontSize: '42px' }
}, parsedChildren);
// equivalent jsx syntax:
// return <span style={{ fontSize: '42px' }}>{parsedChildren}</span>;

} else if (domNode.attribs.class === 'prettify') {
// continue parsing domNode's children with same config
parsedChildren = domToReact(domNode.children, parserConfig);
return React.createElement('span', {
style: { color: 'hotpink' }
}, parsedChildren);
// equivalent jsx syntax:
// return <span style={{ color: 'hotpink' }}>{parsedChildren}</span>;
}
// with ES6 and JSX

// converts dom object to React Elements
import domToReact from 'html-react-parser/lib/dom-to-react';

const html = `
<div>
<p id="main">
<span class="prettify">
keep me and make me pretty!
</span>
</p>
</div>
`;

// parser config
const options = {
replace: (domNode) => {
// do not replace if element has no attributes
if (!domNode.attribs) return;

if (domNode.attribs.id === 'main') {
return (
<span style={{ fontSize: '42px' }}>
{domToReact(domNode.children, options)}
</span>
);

} else if (domNode.attribs.class === 'prettify') {
return (
<span style={{ color: 'hotpink' }}>
{domToReact(domNode.children, options)}
</span>
);
}
}
};

require('react-dom').render(
Parser(html, parserConfig),
render(
Parser(html, options),
document.getElementById('root')
);
// <div>
// <span style="font-size: 42px;">
// <span class="prettify" style="color: hotpink;">
// keep me and make me pretty!
// </span>
// </span>
// </div>
```

You will get the following:

```html
<div>
<span style="font-size: 42px;">
<span class="prettify" style="color: hotpink;">
keep me and make me pretty!
</span>
</span>
</div>
```

## Testing
Expand Down

0 comments on commit c7bfd40

Please sign in to comment.