Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject a React component into HTML

Tags:

reactjs

I am trying to receive a piece of HTML markup from an external source and inject React components into specific parts of it before it gets rendered.

To achieve this I have been playing around with react-html-parser (https://github.com/wrakky/react-html-parser)

I had this example working... although, it feels hacky and cannot possibly the best way to achieve this.

// a simple component
const Image = props => {
    return <img {...props}/>    
};

// this resource comes from an external source and can differ
// ultimately, I would like to be able to target certain elements selecting their data-attributes
// to insert a React component
const externalHTML = '<div class="image"></div>';

// using the react-html-parser library to convert the externalHTML into a React component
const DynamicReactComponent = ReactHtmlParser(externalHTML);

// manually injecting a React component into the dynamically created component
DynamicReactComponent.props.children.push(<Image src="something/anything.jpg" />);

Another example, with a bit more complicated setup;

const externalHTML = '
    <div class="someClass">
        <figure class="image">
            <img src=""/>
            <figcaption></figcaption>
        </figure>
    </div>';

// using the react-html-parser library to convert the externalHTML into a React component
const DynamicReactComponent = ReactHtmlParser(externalHTML);

// way too hacky....
// and it does not fully work
DynamicReactComponent.props.children.map(child => {
    if(typeof child === 'object' && 'type' in child) {
        switch(child.type) {

            case 'img':
                // this cannot be done as it's readonly
                child.props.src = 'something/anything.jpg';
                break;

            case 'figcaption':
                return child.props.children.push(<Text/>)

            default:
        }
    }
});

In this example I wish to add a src to the image element and a caption to the figcaption. The rest of the mark up needs to stay untouched, but should be rendered accordingly. Just to clarify, I have prepared logic to Reactify attributes, e.g. class becomes className.

I know that react-html-parser has a custom way to transform nodes. But this forces me to define in code what the outcome should look like. The HTML I receive from the external source is dynamic and the amount of e.g. div elements (and their attributes) wrapping an image may vary.

I feel a bit lost. What is the best way to achieve this?

like image 564
entiendoNull Avatar asked May 09 '19 06:05

entiendoNull


People also ask

Can we use React component in HTML?

Simply adding React components into HTML code is not possible, because <MyComponent></MyComponent> is not HTML at all, it is JSX.

How do you add a React in HTML?

Just use react-create-app template and the basic html (head, meta) things are already in place, Just modify the src dir to meet you needs. for example the index. js would be something like this, import React from 'react'; import './App.

Can I convert React to HTML?

Yes, both Angular and React apps can be (and usually are) "built" to static HTML, CSS and JS.

How render HTML component React?

React's goal is in many ways to render HTML in a web page. React renders HTML to the web page by using a function called ReactDOM. render() .

How to add React components to a HTML page?

1 Add a DOM Container to the HTML First, open the HTML page you want to edit. ... 2 Add the Script Tags Next, add three <script> tags to the HTML page right before the closing </body> tag: <!-- ... other HTML ... --> <!-- Load React. ... 3 Create a React Component

How to add React components in one minute?

Add React in One Minute 1 Add a DOM Container to the HTML First, open the HTML page you want to edit. ... 2 Add the Script Tags Next, add three <script> tags to the HTML page right before the closing </body> tag: <!-- ... other HTML ... --> <!-- Load React. ... 3 Create a React Component

How do I set the innerHTML of an element in react?

In vanilla javascript, you have the innerHTML property to set or return the HTML content (inner HTML) of an element. In React, you can use dangerouslySetInnerHTML to let React know that the HTML inside of that component is not something it cares about. You can find more information about dangerouslySetInnerHTML in the React official docs.

How to render a string as HTML in react?

Instead, the complete string, including the H1 tags, will be displayed to the user, thanks to React. To render the string as HTML, you need to use the dangerouslySetInnerHTML prop. The dangerouslySetInnerHTML prop was built to present and inject DOM formatted content into the frontend.


1 Answers

You may use ReactDOMServer to inject React elements into HTML markup (ReactDOMServer.renderToString is available in browser too). The step by step algorithm will be:

1) render your React element as a string

2) create a template element and paste loaded HTML into it's innerHTML property (you need template since you want to inject React before HTML will be rendered)

3) inject HTML of React component into specific element inside template

4) render template content on the page

5) hydrate React component if needed

Check this demo on StackBlitz https://stackblitz.com/edit/react-yvncqj

like image 165
Andrei Belokopytov Avatar answered Nov 15 '22 06:11

Andrei Belokopytov