iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🚀

Thoughts on Blog Widgets in the React Era

に公開

In the past, what were called "blog parts" (widgets)—where you could add functionality to your site by pasting some JavaScript—were widely used.

At that time, libraries like jQuery were the mainstream. Even when modifying the DOM, it was usually only partial, and when navigating pages, the standard behavior was for the server to send fresh HTML. Therefore, there were few issues even if you arbitrarily modified the DOM of the received HTML.

However, we are now in the heyday of React. React takes control of the entire DOM (depending on the configuration, of course), and if you use an SPA, React manages all DOM updates. There is no room for the old-style blog parts to intervene in this behavior.

However, there is still a demand for things like blog parts. So, I recently thought about how to provide blog parts in the age of React's dominance and decided to write it down as a note.

First, React has a feature called createPortal that is intended for things like embedding blog parts. Using this feature allows you to prepare a DOM element outside of React's control, which can then be modified freely.

Therefore, you can implement it as follows:

  • Prepare a DOM element outside of React's control
    • I think a div tag with an ID is best, so the following is based on that assumption
      • Of course, ensure the ID is unique by adding a prefix like the service name to avoid collisions
    • You can use createPortal, or if React is only managing a specific div tag, you can create it outside of that
  • Implement the blog part to only modify the contents of the specific ID
    • If the ID doesn't exist, you could treat it as a non-React implementation and specify that the DOM should be added arbitrarily
    • Even if page transitions occur in an SPA, the DOM outside of React's control will not be overwritten, so it can persist

This may be common knowledge to some, but after discussing it with ChatGPT, I was able to come up with a relatively practical strategy, so I'm writing it down as a note.

Discussion