0

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.

2
  • 3
    This is a real "dear god why" ask. Can you not just convert the whole code to React? Commented Mar 16, 2021 at 19:13
  • I'd like to, but apparently this component needs to be very performant and previous attempts at the company weren't as successful in making it both usable and performant. Commented Mar 16, 2021 at 19:31

1 Answer 1

1

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>
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.