Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update CSS variables in React dynamically?

Tags:

css

reactjs

I searched a bit but didnt really find something that directly solved this.

If I have a var in CSS that is set to blue (--color:blue) and say I want to update it to red so that everything that relies on this varible is now changed to red, how would I approach that? For the sake of this discussion, lets assume its defined on the Body in css. Im not supposed to access the document, which is my first thought coming from vanilla JS but I understand in react I should never do that.

like image 765
Sporadic Avatar asked Sep 10 '26 04:09

Sporadic


1 Answers

React is a UI framework, not an application framework. So the simplest thing to do is to wire the ability to change the color into your UI framework by adding some code to your application.

import React from 'react';
import { createRoot } from 'react-dom/client';
// Or use import { render } from 'react-dom'; if you're not on React 18

// Your _application_ logic can do things with the DOM directly
const changeThemeData = (newTheme) => {
  document.body.style.setProperty('--color', newTheme.color);
};

const uiRoot = createRoot(document.getElementById("your-mount-point"));
uiRoot.render(
  <YourApp onThemeChange={changeThemeData} />
)

But if you want to avoid manipulating the DOM at all (because you want to manipulate the DOM for UI reasons and you want to keep all of your UI logic in your UI framework, for example), then the right thing to do is to move your styling from body to yourMainElement:

/* Your CSS File.css */
#the-main-element {
  --color: red;
  /* etc. */
}
function YourApp() {
  const styles = isMonday() ? {"--color": "blue"} : undefined;
  return <div id="the-main-element" style={styles}>Well, well, well</div>
}
like image 117
Sean Vieira Avatar answered Sep 11 '26 17:09

Sean Vieira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!