Guide for using a CSS variable in a dynamic CSS class within a dynamic component

I'm working with library components and running into an issue with CSS when importing the same component multiple times within 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%;
}

Despite setting different colors on import:

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

...both components end up being blue in color!

I've encountered errors when attempting to use style modules. How can I efficiently manage dynamic CSS without resorting to another external library?

Answer №1

When you make changes to the CSS variable/property on the shared top element document.documentElement, it will have an impact on all your Elements.

If you only want these changes to affect your React component, then simply apply them directly to that specific component Element. To access this Element, you can utilize the useRef hook:

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

  const ref = useRef(null);

  useEffect(() => {
    // Make the necessary style modifications on the element or its parent,
    // rather than the common top document
    if (color) ref.current.style.setProperty("--color", color);
    if (size) {
      ref.current.style.setProperty("--size", `${size}px`);
    }
  }, []);

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

Check out the demo here: https://codepen.io/ghybs/pen/WNKdZro


By the way, there appears to be a typo in your CSS: :root pseudo-class should have the colon : as the first character, not the last.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`I am encountering an issue with retrieving the session in nextAuth`

While trying to learn nextAuth from tutorial videos on YouTube, I encountered an issue. Here is my app/api/auth/[...nextauth].js file import NextAuth from "next-auth"; export default NextAuth({ providers: [ CredentialsProvider({ name: ...

Cookie setting issue in Next.js/React: The frustration continues

I'm currently attempting to retrieve a cookie in Next.js using Express, but while the backend functions correctly with Postman and retrieves the cookie token, the frontend is unable to obtain the cookie. Below is my backend code: const express = requi ...

What is the best way to horizontally center my HTML tables and ensure that they all have uniform widths?

I'm currently facing an issue where I'd like to center align all tables similar to the 'Ruby Table.' However, I'm unsure of how to achieve this. You may also observe that some tables have varying widths. What CSS rule can I apply ...

A method for automatically refreshing a webpage once it switches between specific resolutions

On my page www.redpeppermedia.in/tc24_beta/, it functions well at a resolution of over 980px. However, when the resolution is brought down to 768px, the CSS and media queries alter the layout. But upon refreshing the page at 768px, everything corrects itse ...

Enhancing the Calculator Functionality in a React Program

I'm struggling to incorporate a reset button into the input field, similar to CE on a calculator. I'm facing challenges when it comes to integrating it within the existing code structure. import { useRef } from "react"; import './A ...

The latest version of React-native-maps (v0.20.1) is now compatible with expo (v25

Currently, I am working on developing a mobile app using expo v25.0.0 with react native. My react-native version is up to date. However, I have encountered an issue with react-native-maps having dependencies [email protected] and [email protected ...

Is it necessary to use useCallback when executing a function from a child component?

Consideration should be given to using useCallback when ensuring referential equality during parent component renders. However, it's unclear if this is necessary in a scenario where the parent is dealing with a child function. import { ReactNode, useC ...

Warning: Shadcn-UI Form Alert - An element is converting an uncontrolled input to controlled mode

Throughout the course of this project, I found myself repeatedly using const [fileNames, setFileNames] = useState<string[]>([]); and logging the state with console.log(fileNames). However, every time I clicked on the parent element, an empty Array e ...

What makes Next.js API so special?

As I delve into Next.js, I find myself grappling with the concept of server-side rendering (SSR) and API usage. When is it appropriate to utilize the API folder within pages versus deploying my own server along with a database? Would there be any conflic ...

What is the best way to retrieve a comprehensive list of all the synthetic event handlers or listeners that have been registered for a

const Rc = <MyReactComponent onChange={(e) => {console.log(e);} onClick={(e) => { workIt(); }} />; How can I retrieve the list of listeners ['onChange', 'onClick'] for the component Rc? I often come across queries ab ...

What is the best way to handle async/await functions with redux-thunk actions?

action.js export function getLoginStatus() { return async(dispatch) => { let token = await getOAuthToken(); let success = await verifyToken(token); if (success == true) { dispatch(loginStatus(success)); } else { console.lo ...

Creating GraphQL from a Mongoose model: A step-by-step guide

I'm currently utilizing graphql and mongodb to add a specific object to the database. While using the same method to add an object, this particular one has a nested structure. package.json { "name": "workplaces", "versi ...

ReactJs allows for fluid scroll animations that persist as long as the mouse is clicked or a button

Just some background information: I'm aiming to replicate the scrolling effect seen in Etsy's product image thumbnails carousel. Essentially, when you hover over the top part of the div, it automatically scrolls down until the last image is reve ...

The variablewidth feature in Slick Carousel is malfunctioning

I've integrated slick slider 1.8.1 into my Rails app (v.5.2.0) and I'm encountering an issue with variablewidth set to true. My expectation was to achieve a layout similar to the example shown here: https://i.sstatic.net/5QFRx.jpg However, what ...

Tips for displaying all 'ul li' lists in media queries to ensure responsiveness in design

When I view my navigation bar snippet on desktop mode, it displays all the list items. However, when I adjust the browser width to fit my media queries, only the Home list is shown in the nav bar. Here's an example of the issue: Before Clicking the ...

I am unable to display an external site image in a Direct Path using Next.js

I am using Next.js version 13.4.4. There seems to be an error here, and it appears that it is not coming from a static image. Error: An object should only be passed to the image component src parameter if it comes from a static image import. It must inc ...

Position a span within a container div and ensure that it remains centered even in cases of overflow

I need assistance with centering text horizontally next to an image inside a container div that is 40px x 40px. The anchor tag contains the image with matching dimensions, and below it is a span with text. I've tried using text-align: center, adjustin ...

Creating inner borders on a pie chart with HTML and CSS: A step-by-step guide

After putting my coding skills to the test, I successfully crafted a stunning pie chart using only HTML and CSS. https://i.sstatic.net/5xCbl.png Here's the code snippet I tinkered with: HTML - <div class="pie-chart"></div> CS ...

Changing the color of a placeholder using Javascript: A step-by-step guide

I've been searching online without any luck so far. I'm attempting to change the placeholder color of a text box using JavaScript, but I'm not sure how to go about it. I already have a color picker that changes colors. If my CSS looks somet ...

JavaScript for controlling first-person movement with a mouse

Currently, I am working on implementing a first person movement feature using the mouse. While I have successfully implemented it using the keyboard, I am facing challenges with the mouse input. The issue arises from the ambiguity in movement directions ca ...