score:10

First of all, your desired embedded / initialization format (which is of course typical for embeddable widgets) requires that the loaded script creates the Example global object, on which you can then invoke .init(), which then renders your widget html into the tag specified in selector.

Next creates a full page, not an object that can be called as described above.

To change this you need to override the Next server to bypass the whole app.render() process for specific urls, and instead create the Example object, which does its own call to ReactDOM.render() on .init().

You also need to address the two possible scenarios that the web page where your widget is embedded can be a React-based page or not. So you either need to use already loaded ReactDOM or make the browser load React before you can render your widget.

While all this is doable, it is not easy to make robust, and doing it inside NextJS makes it more cumbersome. My advice would be to structure the code of your NextJS app in such a way that the parts you need in the widget are components that you can use both in the NextJS main app and in a separate embeddable widget using plain CRA.

Some further reading:

https://selleo.com/blog/how-to-create-embedded-react-widget (not the iFrame parts though)

https://meda.io/embed-react-into-an-html-web-page/


Related Query

More Query from same tag