简体   繁体   中英

How to apply CSS variable on dynamic CSS class in dynamic component

I have library components, and I create some components, but I have a problem with CSS when importing twice a component in a parent component with different styles.

import "../myCss.css"
const CircleComponent = ({size , color}) => {
  useEffect(() => {
    if (color)
      document.documentElement.style.setProperty(
        "--color",
        color
      );
    if(size) {
      document.documentElement.style.setProperty(
        "--size",
        `${size}px`
      );
    }
  }, [])

  return <div className="circle"></div>
}

CSS:

root: {
 --color: black;
 --size: 40px
}

.circle{
  height: var(--size);
  width: var(--size);
  background-color: var(--color);
  border-radius: 50%;
}

When I import this component and set a different color:

<>
 <CircleComponent color="red" />
 <CircleComponent color="blue" />
</>

...both components get blue color!

I couldn't use the style module, have many errors!

How can I best use dynamic CSS? Without another library?

Because you modify the CSS variable/property on the common top document.documentElement , it will affect all your Elements.

If you want to apply it only on your React component, then simply set it on that component Element. To get a handle to such Element, you can use the useRef hook:

const CircleComponent = ({ size, color }) => {

  const ref = useRef(null);

  useEffect(() => {
    // Modify the property on the element or a parent,
    // not on the common top document
    if (color) ref.current.style.setProperty("--color", color);
    if (size) {
      ref.current.style.setProperty("--size", `${size}px`);
    }
  }, []);

  // Attach the ref with the ref special prop
  return <div ref={ref} className="circle"></div>;
};

Demo: https://codepen.io/ghybs/pen/WNKdZro


BTW, there is a typo in your CSS: :root pseudo-class has the colon : as 1st character, not last.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM