skip to Main Content

I would like to know how can I inject dynamically component from text with html and execute it.

I would like, for example, replace <abbr></abbr> by a custom component.

Currently, I have a text:

<h1>Lorem</h1> ipsum <abbr title="">Test1</abbr> dolor sit amet <abbr title="">Test2</abbr> lorem ipsum <abbr title="">Test3</abbr>.

I would like to inject a CustomComponent to replace <abbr></abbr>:

let injectComponent = (text) => {
    let replacedText;

    const regex = /<abbr title="">(.*?)</abbr>/g;

    replacedText = text.replace(regex,function(_,match) {
        return  `<CustomComponent data="${match}" />`
    })
    
    return replacedText;
}

And I use injectComponent in:

<span className="text-slate-900"
    dangerouslySetInnerHTML={{ __html: injectComponent(post.content) }}>
</span>

But the CustomComponent is not render. In the dom, there is customcomponent and it’s not show on the front.

2

Answers


  1. Please see my solution below. I hope it helps you.
    I noticed an error in this code.

    replacedText = text.replace(regex,function(_,match) {
            return  `<CustomComponent data="${match}" />`
        })
    

    CustomComponent is being converted to string. React does not recognize it as a React Element. React only supports html elements so <CustomComponent data="${match}" /> will not work like you thought.

    Code Sandbox

    let post = {
      content: `Lorem ipsum dolor sit amet <abbr title="">Test</abbr>`
    };
    
    const CustomComponent = ({ data }) => {
      // You can add more functionalities here.
      return (
        <span
          className="text-slate-900"
          dangerouslySetInnerHTML={{ __html: data }}
        />
      );
    };
    
    let InjectComponent = ({ text, re = /<abbr title="">(.*?)</abbr>/g }) => {
      const [firstToken, match, lastToken] = text.split(re);
      return [firstToken, <CustomComponent data={match} />, lastToken];
    };
    
    export default function App() {
      return (
        <InjectComponent text={post.content} re={/<abbr title="">(.*?)</abbr>/g} />
      );
    }
    Login or Signup to reply.
  2. In React, you can use the dangerouslySetInnerHTML attribute to dynamically inject HTML code, and use a custom component to replace the tag with your desired component.

    1. Define the custom component you want to use.
    import React from 'react';
    
    const CustomComponent = () => {
      return <div>This is a custom component</div>;
    };
    1. Create a React component that contains the HTML code you want to dynamically inject.
    import React from 'react';
    
    const MyComponent = () => {
      const htmlCode = '<p>This is some text with an <abbr>abbreviation</abbr></p>';
      
      const getInnerHTML = (htmlCode) => {
        // Replace <abbr> tag with CustomComponent
        const modifiedHTML = htmlCode.replace(/<abbr>/g, '<CustomComponent>');
        return {__html: modifiedHTML};
      };
      
      return (
        <div dangerouslySetInnerHTML={getInnerHTML(htmlCode)} />
      );
    };
    1. Render the MyComponent component in your app
    import React from 'react';
    import ReactDOM from 'react-dom';
    import MyComponent from './MyComponent';
    
    ReactDOM.render(
      <MyComponent />,
      document.getElementById('root')
    );

    With these steps, you can dynamically inject HTML code with React and replace the tag with your custom component. When the MyComponent component is rendered, the HTML code is injected and the tag is replaced with your custom component, which can be executed and displayed in the browser.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search