Skip to content Skip to sidebar Skip to footer

How To Put React Component Inside Html String?

I have: an array of HTML strings, eg ['

Hi', '

']. I want to place in between them (thus achieving a layout that would be in jsx:

Solution 1:

You might want to take a look at html-to-react.

This library converts the string to a node tree of DOM elements, then transforms each node to a React element using a set of instructions that you define. I believe that it depends on the string being valid markup though, so you might have to change "<h1>Hi<MyReactComponent/></h1" to something like "<h1>Hi<x-my-react-component></x-my-react-component></h1>.

Example:

import { Parser, ProcessNodeDefinitions } from"html-to-react";
importMyReactComponentfrom"./MyReactComponent";

const customElements = {
    "x-my-react-component": MyReactComponent
};

// Boilerplate stuffconst htmlParser = newParser(React);
const processNodeDefinitions = newProcessNodeDefinitions(React);
functionisValidNode(){
    returntrue;
}

// Custom instructions for processing nodesconst processingInstructions = [
    // Create instruction for custom elements
    {
        shouldProcessNode: (node) => {
            // Process the node if it matches a custom elementreturn (node.name && customElements[node.name]);
        },
        processNode: (node) => {
            letCustomElement = customElements[node.name];
            return<CustomElement/>;
        }
    },
    // Default processing
    {
        shouldProcessNode: () =>true,
        processNode: processNodeDefinitions.processDefaultNode
    }
];

exportdefaultclassMyParentComponentextendsComponent {
    render () {
        let htmlString = "<h1>Hi<x-my-react-component></x-my-react-component></h1>";
        return htmlParser.parseWithInstructions(htmlString, isValidNode, processingInstructions);
    }
}

The essential part here is processingInstructions. Every node in the DOM tree is checked against each instruction in the array, starting from the top, until shouldProcessNode returns true, and the node is transformed to a React element by the corresponding processNode function. This allows for rather complex processing rules, but it quickly gets a bit messy if you want to process nested custom elements. The result of the example is the equivalent of

<h1>
    Hi
    <MyReactComponent/></h1>

in JSX syntax. Hope this helps!

Post a Comment for "How To Put React Component Inside Html String?"