A few days ago I added a cool comments widget to my NextJS/React blog. The widget installation instructions required me to add a
script tag to the
body in the place I wanted the widget to be. The script would then use
document.insertAdjecentHTML to insert the widget right after itself in the DOM and later remove itself.
So far so good, but I had never added a script to the
body in a React app before, and wasn’t sure how to do it. Long story short I figured out how to do it properly, but was left wondering why simply putting the script in the returned React element tree wouldn’t work. React added the
script to the DOM, but the script did not seem to work. (It wasn’t downloading the script from
That led me to a reverse engineering endeavor to see what exactly React does with React elements of type “script”. What I found is that React creates a “temporary” div, adds a script node to it via
innerHTML, removes the script node from that div and later inserts the script into the DOM. Because it was originally inserted via innerHTML, it is for security reasons “inert” or “ball-less” as my friend would say.. So that is the answer.
But now my question is (see attachment) : why do the react engineers concatenate a string together before setting its value to
innerHTML ? Couldn’t they have used an unconcatenated string?