I know direct DOM manipulation should be avoided at all costs in React, and normally I wouldn't even think of using it. I've recently been working on some component packages for use within my company. All of our projects utilize different CSS solutions, so I need to come up with a singular method for handling shared components.
I'd prefer not to have dozens of import '../..css' statements for every separate component package, and don't want to bundle all the components/css into one lib because some of these won't be used in specific projects. So as far as I can tell, the alternatives are to either use a CSS-in-JS library and add it as a dependency, use inline styles (style={{}}), or just use <style> tags in the body.
I know the last two aren't really encouraged, and I'd prefer to avoid adding another dep if possible. So, I started looking into how these CSS-in-JS libraries for React go about getting the stylesheets in the <head> of the document.
Turns out, every CSS-in-JS library I checked is just using direct DOM manipulation, i.e. document.querySelector('head')?.innerHTML += '<style>...</style>' with cleanup in the useEffect return, which makes alot of sense, I don't know why I assumed they were accomplishing style injections in a more 'React' way. I'm used to NextJS and next/head and sometimes forget that vanilla React doesn't really provide you with a way to update the <head>.
I have been considering just handling styles the direct way, but something about this just feels off to me. From everything I know, direct DOM manipulation and React should not be utilized together. But at the same time, this seems to be a specific scenario where it is alright to use it, especially considering these CSS-in-JS libraries are reliably doing so.
So, should doing this be avoided at all costs? Or is this one of the few situations where it is acceptable and makes sense?