简体   繁体   中英

Is there a way to insert stylesheet with variable values in ReactJS?

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

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>

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.

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" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM