CodexBloom - Programming Q&A Platform

CSS Custom Properties implementation guide with Dynamic Content in React 18

πŸ‘€ Views: 5 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-06
react css custom-properties JavaScript

I'm sure I'm missing something obvious here, but I'm sure I'm missing something obvious here, but I've searched everywhere and can't find a clear answer. I'm working on a React 18 application where I'm trying to use CSS custom properties (variables) to dynamically change the theme colors based on user selection. However, I'm working with an scenario where the CSS variables do not seem to update when the component re-renders with new values. For instance, I have a button that lets users switch between light and dark themes, and I'm attempting to set the CSS variables in the `useEffect` hook. Here’s a simplified version of my code: ```jsx import React, { useEffect, useState } from 'react'; const ThemeToggle = () => { const [theme, setTheme] = useState('light'); useEffect(() => { document.documentElement.style.setProperty('--primary-color', theme === 'light' ? '#fff' : '#333'); document.documentElement.style.setProperty('--secondary-color', theme === 'light' ? '#000' : '#fff'); }, [theme]); return ( <div> <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>Toggle Theme</button> <p style={{ color: 'var(--primary-color)' }}>Current Theme: {theme}</p> </div> ); }; export default ThemeToggle; ``` When I toggle the button, the text updates correctly, but the background color I set in my CSS file (using the variables) does not change. In my CSS, I have: ```css :root { --primary-color: #fff; --secondary-color: #000; } body { background-color: var(--primary-color); color: var(--secondary-color); } ``` There are no errors in the console, and I’ve checked that my CSS file is properly linked. I even tried adding a second `useEffect` that logs the values of the variables, but they appear to hold old values. Am I missing something in my approach to updating CSS variables dynamically? Any suggestions would be appreciated! My development environment is Ubuntu. Any help would be greatly appreciated! This is part of a larger CLI tool I'm building. Any help would be greatly appreciated! Any pointers in the right direction? This is for a desktop app running on Ubuntu 20.04. Any ideas how to fix this?