Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - Return a component from innerHtml function

How to return a component through the JS innerHTML() function? With the code below, it is returning on the browser screen: [object Object]

document.getElementById("threeline-icon").innerHTML =
        `${<ThreelineIcon />}`
        ;
    }

Component Code:

import React from 'react'

const ThreelineIcon = () => {
  return ( 
    <div>
    <span className="top"></span>
    <span className="middle"></span>
    <span className="bottom"></span>     
    </div>
  )
}

export default ThreelineIcon
like image 601
claudiopb Avatar asked Oct 22 '25 12:10

claudiopb


1 Answers

You can use the renderToString method used by server side rendering to convert a React component into HTML. But please keep in mind that this works only if your Component is static, I mean any events or lifecycle methods (except componentWillMount) will not work.

import ReactDOMServer from 'react-dom/server';
document.getElementById("threeline-icon").innerHTML =
    ReactDOMServer.renderToString(<ThreelineIcon />);
like image 132
AvcS Avatar answered Oct 24 '25 04:10

AvcS