Sporadic
Sporadic

Reputation: 260

update CSS variables in React dynamically?

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.

Upvotes: 2

Views: 3338

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 160053

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>
}

Upvotes: 2

Related Questions