Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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" />
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!