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.
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.
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.
Create a React Component named ReactComponent.js and write the following code in it.
Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
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.
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.