skip to Main Content

I have a component that I want to be able to use multiple times but have some of the css be different based props passed in. The problem is doing the way that I have changes it across all of my component.

import React, { useEffect, useState } from "react";

export function Gauge(props) {
    useEffect(() =>{
        getComputedStyle(document.documentElement).getPropertyValue('--fillColor');
        document.documentElement.style.setProperty('--fillColor', props.color);
    }, [])

    return (
        <div className="gauge">
             <div className="gaugeFill"></div>
        </div>
    );
}
.gaugeFill {
    width: 100%;
    position: absolute;
    bottom: 0px;
    background: var(--fillColor);
}

2

Answers


  1. import React, { useEffect, useState } from "react";
    
    export function Gauge(props) {
        const [fillColor, setFillColor] = useState(''); // State to hold fill color
    
        useEffect(() => {
            setFillColor(props.color); // Update fill color based on prop change
        }, [props.color]);
    
        return (
            <div className="gauge">
                 <div className="gaugeFill" style={{ background: fillColor }}></div>
            </div>
        );
    }
    
    Login or Signup to reply.
  2. I think that easiest solution is to set that css variable(if you want is as var()) in inline style

    import React, { useEffect, useState } from "react";
    
    export function Gauge(props) {
        return (
            <div className="gauge" style={{ "--fill-color": props.color } as React.CSSProperties}>
                 <div className="gaugeFill"  ></div>
            </div>
        );
    }
    

    otherwise you can just set color in gaugeFill

    import React, { useEffect, useState } from "react";
    
    export function Gauge(props) {
        return (
            <div className="gauge">
                 <div className="gaugeFill" style={{background: props.color}}  ></div>
            </div>
        );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search