Search code examples
javascriptreactjstypescriptjsxtsx

Turning a TSX/JSX React into a string or DOM element


So I have an unusual requirement from my tech lead. I essentially need to turn a callback that returns JSX and turn the output into an HTMLElement or a string.

The thing is that we're building a reusable, low level infinite scroll component that reuses the DOM so that only 20 DOM elements are ever present on the componenent. Here is the codepen for the PoC I was sent for this:

https://codepen.io/hemant30/pen/rNWQEZy?editors=0010

The codepen works, but doesn't handle anything in React, it's purely DOM manipulation.

The callback the component receives is something like this:

(data: any) => {
      return (
        <div key={data.id}>
          {data.id} - {data.name}
          <br />
          <a href="#">Text</a>
        </div>
      );
    }

The idea is to be able to then, when using this callback internally, turn it into something that can be added to an element through dangerouslySetInnerHTML.

I have tried multiple things and approaches, but my approaches haven't been approved. So I turn to you to see if there is a way to do this or not.


Solution

  • You can check renderToStaticMarkup method, it can transform jsx into string html.

    import ReactDOMServer from 'react-dom/server'
    
    const htmlString = ReactDOMServer.renderToStaticMarkup(
        <div>
             <Component/>
             /* etc. */
        </div>
    );