1

I have library components, and when I create some components, I have a problem with CSS when importing a component twice 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 correctly use dynamic CSS here without another library?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.