react-html-parser icon indicating copy to clipboard operation
react-html-parser copied to clipboard

How to create new nodes?

Open mraak opened this issue 6 years ago • 1 comments

I would like to use text node's data, to split it into multiple spans.

<p>hello world</p>

would be turned for example into:

<p><span>hello</span> <span>world</span></p>

I used the transform method to split the node.text with regex . and surround every word with , but what I'm getting is tags literally written into browser, or I get [Object object] instead of .

I tried all of the below and none of them worked.

const transform = (node, index) => {
  if (node.type === "text") {
    const regx = /(\w+)/g;
    node.data = node.data.replace(regx, "<span>$1</span>");
    return convertNodeToElement(node, index, transform);
  }
};

const transform = (node, index) => {
  if (node.type === "text") {
    const regx = /(\w+)/g;
    node.data = node.data.replace(regx, <span>$1</span>);
    return convertNodeToElement(node, index, transform);
  }
};
const transform = (node) => {
  if (node.type === "text") {
    const regx = /(\w+)/g;
    return node.data.replace(regx, <span>$1</span>);
  }
};

mraak avatar Oct 14 '18 12:10 mraak

I have a similar problem:

I am receiving HTML that isn't completely correct, i.e. there are <li> nodes but no wrapping <ol> or <ul> tags. Now I would like to find all list items and wrap them with one of the list elements.

Is this possible?

EDIT: I figured out how to do it:

import { existsOne, findAll, appendChild, removeElement } from 'domutils';

...

function preprocessNodes(nodes) {
    if (existsOne((node) => (node.name === 'li'), nodes)) {
        // Create new list
        const list = { type: 'tag', name: 'ul', attribs: {}, children: [] };
        const items = findAll((node) => (node.name === 'li'), nodes);
        items.forEach((node) => removeElement(node));
        items.forEach((node) => appendChild(list, node));
        // Remove items from DOM and replace with list
        nodes.splice(nodes.indexOf(items[0]), items.length, list);
    }
    return nodes;
}

MLNW avatar Mar 23 '20 10:03 MLNW