CodexBloom - Programming Q&A Platform

CSS custom properties implementation guide dynamically with JavaScript

šŸ‘€ Views: 82 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-05
css javascript styled-components react JavaScript

I'm sure I'm missing something obvious here, but I'm trying to use CSS custom properties (variables) to manage theme colors in my web application, but I'm running into issues when attempting to update these properties dynamically with JavaScript. My setup uses React 17 and I'm employing styled-components to handle CSS-in-JS. I'm defining a CSS custom property like this: ```css :root { --main-bg-color: #3498db; } ``` Then, in my styled component, I use it as follows: ```javascript const Container = styled.div` background-color: var(--main-bg-color); `; ``` When I attempt to change the custom property using JavaScript like this: ```javascript document.documentElement.style.setProperty('--main-bg-color', '#e74c3c'); ``` I expect the background color of the `Container` to change accordingly. However, it does not update, and the background remains the original blue. I've checked that the JavaScript is being executed correctly and the new value seems to be applied as I can see it in the browser's Developer Tools under the `:root` styles. I also attempted to force a re-render of the React component, but that didn't help either. Is there something I’m missing in the way styled-components applies the styles or how the CSS custom properties are being set? Any insight would be greatly appreciated! My development environment is Windows.