Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda