Friday, November 15, 2024
Google search engine
HomeLanguagesHow to put ReactJS component inside HTML string ?

How to put ReactJS component inside HTML string ?

The following approach covers how to put React Component into HTML String by parsing the HTML String into DOM using the html-to-react module.

https://www.npmjs.com/package/html-to-react

It is a lightweight library that is responsible for converting raw HTML to a React DOM structure. 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.

For example, if we have a component named ReactComponent and an HTML string “<div> Hi <MyReactComponent/> </div>”, now we can convert it by using the above library.

Creating React Application And Installing Module:

  • Step 1: Create a React application using the following command.

    npx create-react-app foldername
  • Step 2: After creating your project folder i.e. foldername, move to it using the following command.

    cd foldername
  • Step 3: After creating the ReactJS application, Install the html-to-react module using the following command.

    npm i html-to-react

Project Structure: It will look like the following.

Example: 

Create a React Component named ReactComponent.js and write the following code in it.

ReactComponent.js




export default function ReactComponent() {
    return(
        <div>
            <p>
                Hello from React Component
            </p>
  
        </div>
    )
}


Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

App.js




import { Parser, ProcessNodeDefinitions } from "html-to-react";
import ReactComponent from "./ReactComponent";
import React, { Component } from 'react';
  
const customElements = {
  "my-react-component": ReactComponent
};
  
// Boilerplate stuff
const htmlParser = new Parser(React);
const processNodeDefinitions = new ProcessNodeDefinitions(React);
function isValidNode() {
  return true;
}
  
// Custom instructions for processing nodes
const processingInstructions = [
  // Create instruction for custom elements
  {
    shouldProcessNode: (node) => {
      // Process the node if it matches a custom element
      return (node.name && customElements[node.name]);
    },
    processNode: (node) => {
      let CustomElement = customElements[node.name];
      return <CustomElement />;
    }
  },
  // Default processing
  {
    shouldProcessNode: () => true,
    processNode: processNodeDefinitions.processDefaultNode
  }
];
  
export default class MyParentComponent extends Component {
  render() {
    let htmlString = "<div>Hi<my-react-component></my-react-component></div>";
    return htmlParser.parseWithInstructions(htmlString, 
      isValidNode, processingInstructions);
  }
}


Explanation: 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 the following code in JSX syntax.

<div>
    Hi
    <ReactComponent/>
</div>

Step to Run Application: Run the application using the following command from the root directory of the project.

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output.

Output

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments