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

CSS3 pulsating circular Firefox bug

I am currently working on a CSS3 pulsing circle (animating scale to 1.1). To address a jumpy animation issue in Firefox, I have added a slight rotation. animation: button_pulse 2s infinite ease-out; transform: scale(1.1) rotate(0.1deg); Despite this adju ...

Modify the readonly property of an input element in ReactJS

I am looking to manipulate attributes on an HTML input element. Here is what I have attempted: constructor(props) { super(props); this.state = {inputState: 'readOnly'}; } And within the render function: <input className="form-contr ...

Consider utilizing divs in a similar manner to tables

I typically use tables to align images and text, but they don't work well on mobile devices. I'd like to switch to using CSS and DIVs instead, even though I have no experience with them. My goal is to center three pictures with text above each o ...

Incorporating a YouTube or Vimeo video while maintaining the proper aspect ratio

On my video page, I embed Vimeo videos dynamically with only the video ID. This causes issues with the aspect ratio as black bars appear on the sides due to the lack of width and height settings. The dynamic video ID is implemented like this: <iframe ...

Discover the Steps to Navigate a Mobile App Installed on Your Phone Directly from Your Browser

Looking for a way to navigate to my React Native apps using two different scenarios. I have developed web apps with ReactJS. If the mobile app is not installed and I enter an URL like "https://mywebpage.com" in the mobile browser, it redirects to the Goo ...

Is it possible to execute an onClick event and a <NavLink to="/Scooters"> simultaneously?

Is it feasible in React to both filter my database and redirect to another route upon clicking the search button? I am currently employing <BrowserRouter>. It would also be advantageous if this redirection could occur directly from the onClick even ...

Is there a way to align these blocks in a single row?

Having trouble aligning these buttons horizontally. Any suggestions? I've been tinkering with this for a couple of hours now, so decided to seek help here. The desired effect should resemble the image below, but it's not quite there yet. Thank yo ...

When it comes to designing responsive websites, the use of `@

Being new to CSS, I am open to criticism and feedback. @media (max-width: 735px) {... } @media (min-width: 735px) {... } @media (width: 320px) {... } @media (width: 360px) {... } @media (width: 375px) {... } @media (width: 414px) {... } I have tried us ...

Techniques for positioning text beside an image in a floating block

Despite experimenting with various display settings such as block and inline for text, I am still facing issues. Please take a look at my website: ...

Using CSS to leverage the power of both Grid and Flex simultaneously

Help Needed: CSS Challenge! I'm not a fan of CSS and can't seem to crack this code conundrum. Here's what I want the end result to look like: Current Situation: #newOrderControl { border-style: solid; border-color: black; b ...

Encountered an issue while attempting to generate an application with create-react-app

After installing yarn, updating node and npm, clearing the cache, I am still encountering the same errors. Command used: create-react-app confusion <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7954540a1a0b10090d0a540f1c0b0a1 ...

Can animations be stacked in a queue while using velocity.js?

I'm currently tackling a project involving a push menu. When the content div slides over, the menu buttons come in with a slight animation as they appear on the screen. However, if the user rapidly opens and closes the menu multiple times, the items o ...

Getting the initial date of the upcoming month in JavaScript

I'm trying to figure out how to get the first day of the next month for a datePicker in dd/mm/yyyy format. Can anyone help? Here's the code I currently have: var now = new Date(); if (now.getMonth() == 11) { var current = new Date(now.getFu ...

What is causing the collapsed-animation to malfunction in Vue3?

Why won't the transition animation function in vue3js? The animation does not appear to be working for me. I've implemented this library https://github.com/ivanvermeyen/vue-collapse-transition <template> <nav class="navbar color-d ...

How to turn off validation for md-input-container in Angular 2

While working on a form in Angular 2, I encountered an issue when adding the required attribute to my <input>. The problem resulted in unwanted margins as shown in this image: I am seeking a solution to only apply the second red margin to the input ...

jQuery plugin stops functioning properly following the use of the jQuery display block method

In my project, I am exploring the use of divs as tabs with jQuery. Within these divs, I also want to incorporate another jQuery plugin. Currently, I have manually created these div tabs using jQuery and set the default style for second and subsequent divs ...

Tailwind - make sure the dropdown list is always on top of all other elements

Having an issue configuring the position of a dropdown list. The objective is to ensure it stays on top of all elements, however, when inside a relative positioned element, it ends up being obscured by it. Here's an example code snippet to illustrate ...

What is the best way to align the 'Typography' component in the center?

Attempting to center it using flexbox with justify-content did not yield the desired result. I also tried replacing the Typography component with a div tag, but still no success. import {AppBar,Zoom,Toolbar,Typography,CssBaseline,useScrollTrigger,Fab,ma ...

Using dangerouslySetInnerHTML in React within a Fragment

In my current project, I have a specific requirement where I need to format text in React and also include HTML rendering. Here's an example of what I'm trying to accomplish: import React, {Fragment} from "react"; import {renderToString} from " ...

Obtaining information upon the loading of a Modal in a Next.js application

I am currently developing a feature for my application that allows users to add a new project to a timesheet system. To achieve this, I have created a Modal with a form inside. The form includes a Select field that should display all existing user names f ...