CodexBloom - Programming Q&A Platform

CSS Custom Properties implementation guide in Styled Components with React 18

πŸ‘€ Views: 61 πŸ’¬ Answers: 1 πŸ“… Created: 2025-07-27
react styled-components css JavaScript

I tried several approaches but none seem to work. I'm relatively new to this, so bear with me... Quick question that's been bugging me - I'm working with an scenario where CSS custom properties (variables) defined in a styled-component are not updating dynamically when their values change... I have a simple React component where I'm trying to set a CSS variable based on a prop, but it seems to retain the initial value after the first render. Here’s a simplified version of my component: ```javascript import styled from 'styled-components'; const DynamicDiv = styled.div` --main-color: ${(props) => props.color}; background-color: var(--main-color); width: 100px; height: 100px; `; const MyComponent = ({ color }) => { return <DynamicDiv color={color} />; }; export default MyComponent; ``` I expect that when I change the `color` prop, the background color of the `DynamicDiv` should reflect that change. However, it appears to only work with the initial value when the component mounts. I've tried using a `useEffect` to log the current value of the `color` prop, and it updates correctly, but the CSS variable does not respond to those updates. Here's the effect I implemented: ```javascript useEffect(() => { console.log(`Current color: ${color}`); }, [color]); ``` Additionally, I've checked that React and Styled Components versions are up to date. I’m using React 18.0.0 and styled-components 5.3.3. Is there a known scenario with dynamic CSS variables in styled-components, or am I missing something in my implementation? Any insights would be greatly appreciated! This is part of a larger application I'm building. This is my first time working with Javascript 3.11. Any pointers in the right direction? Is this even possible?