How can I insert <style>
to the DOM in a ReactJS project where the values of the stylesheet are dynamic coming from the database.
I have the following simplified scenario:
<button class="buy-now-button">Buy now</button>
Note: I have no access to modify the HTML or JSX element, the solution needs to be CSS only, and based on the class name that the button has.
I want to be able to add CSS properties like background, color, border to element with CSS class name .buy-now-button
What I need in terms of the stylesheet is:
<style>
.buy-now-button {
color: button.color; // where button.color value comes from DB
background: button.background; // where button.background value comes from DB
}
</style>
And then, that style should be inserted in the DOM.
Does ReactJS offer a mechanism to insert styles to the DOM? How could I solve this use case?
Many thanks
CodePudding user response:
This whole thing is certainly an antipattern, as any time you are doing any sort of direct DOM manipulation with React you are abusing the way in which it is supposed to be used, but you could inject a <style>
block a single time with the colors desired:
function injectStylesheet() {
const ss = document.createElement('style')
ss.innerText = 'body { background-color: pink; }';
document.head.append(ss);
}
<button onClick="injectStylesheet()">add stylesheet</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
While you could instead change the colors directly by finding the element and updating its style
attribute, you would have to do this on every render, which is just a needless performance hit.
CodePudding user response:
How about if you use a CDN to download a css file?
You wouldn't need to even do this within any React code. You could simply include the following in your index.html:
<link rel="stylesheet" type="text/css" href="SOME-CDN-URL" />