1
votes

I am using Wordpress as my CMS and creating some of the pages in React and rendering it. I have a use case where i need to render HTML DOM Node inside of my React Component. I am getting the DOM Node with the help of querySelector() which returns me the DOM node. In React i am trying to render it using React.createElement. But it renders as [object HTMLDivElement] on my page.

 render() {
      const { reactPages } = this.props;
      const innerPages = React.createElement('div', {id: "myDiv"}, `${reactPages.children[0]}`);
      
      return (
        <div className="react-cmp-container">
          <h3>React Container</h3>
          { innerPages }
        </div>
      )
    }
  }

The other thing i tried was using the dangerouslySetInnerHTML:

 rawMarkUp = () => {
      const { reactPages } = this.props;

      return {__html: reactPages}
    }

    render() {

      const innerPages = React.createElement('div', {id: "myDiv"}, )
      
      return (
        <div className="react-cmp-particle-container">
          <h3>React Particle Container</h3>
          <div dangerouslySetInnerHTML={this.rawMarkUp()}></div>
        </div>
      )
    }

This is the type of DOM Node that i am getting and passing it as props to my Component. enter image description here

1
Have you tried using the React.render() function to make sure you are rendering the DOM element.shn
@shn In my ReactDOM.render i am rendering my component where i am trying to print the DOM Node. ReactDOM.render(<MyComponent />, element);tkamath99
@shn Even if i try to render the Node in React.render is gives an error as : Objects are not valid as a React child (found: [object HTMLDivElement])tkamath99
Please reproduce in codesandboxDennis Vash

1 Answers

1
votes

This is not recommended to to. It might cause many kinds of trouble later. Anyway, ...

querySelector() returns a DOM-element (or collection of such).

1. React.createElement

React.createElement does not work, because it expects another React.Element, or a string, not a DOM-element.

2. dangerouslySetInnerHTML

dangerouslySetInnerHTML does not work, because it expects a HTML string, not a DOM-element.

You could use domElement.innerHTML and put the HTML string into dangerouslySetInnerHTML, but that might not represent the DOM element as you want it.

3. useRef

You could add a ref to some element that is rendered by React. This gives you access to the corresponding DOM-element (rendered by React), and you can inject your DOM-element (returned by querySelector()) using normal DOM methods.

This disables React to "track what's going on", and you might experience inconsistent state and hard-to-understand bugs.

e.g.:

export const StaticHtml = (props)=>{
    const ref = useRef();

    useEffect(() =>{
        var elm = document.getElementById('some-static-html');
        ref.current.appendChild(elm);
    }, []);

    return (<div ref={ ref }>
        some div
    </div>);
};