Getting the value of a CSS Variable from Radix UI Colors with Javascript/Typescript: A step-by-step guide

Currently, I am attempting to dynamically retrieve the Radix Colors values in JavaScript. The reason for this requirement is that I generate these colors based on user input, resulting in values that are variable. As a result, I cannot hardcode the values.

My aim is to access the values stored inside a CSS variable, as the variables remain constant while the values change.

Despite my efforts within the component to retrieve the values, I always receive an empty string. I even used a setTimeout function to ensure that the variable is declared before logging the values.

const [accent7Color, setAccent7Color] = useState('');
  const [accent8Color, setAccent8Color] = useState('');

  useEffect(() => {

    // Attempted with document.documentElement as well
    const rootStyles = getComputedStyle(document.body);

    const accent7 = rootStyles.getPropertyValue('--accent-7').trim();
    const accent8 = rootStyles.getPropertyValue('--accent-8').trim();

    setAccent7Color(accent7);
    setAccent8Color(accent8);
    setTimeout(() => {

      console.log('Accent 7 Color:', accent7);
      console.log('Accent 8 Color:', accent8);
      console.log(accent7Color);
      console.log(accent8Color);

    }, 4000);
  }, []);

It's worth noting that this code is not located at the root of the application, which might be causing the issue as it's deeply nested within the app.

I also attempted to define "rootStyles" outside of the useEffect and include it in the dependency array to ensure the function runs only when rootStyles is defined or its value changes, but this did not solve the problem. I'm stuck and in need of help.

I have exhausted the methods mentioned above, and I couldn't find any other solutions online. Any assistance would be greatly appreciated.

Answer №1

The script executes once the CSS variables are updated in the DOM.

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

const ColorComponent = () => {
  const [accent7Color, setAccent7Color] = useState('');
  const [accent8Color, setAccent8Color] = useState('');

  useEffect(() => {
 setTimeout(() => {
      
      const rootStyles = getComputedStyle(document.documentElement);

      const accent7 = rootStyles.getPropertyValue('--accent-7').trim();
      const accent8 = rootStyles.getPropertyValue('--accent-8').trim();

      setAccent7Color(accent7);
      setAccent8Color(accent8);

      console.log('Accent 7 Color:', accent7);
      console.log('Accent 8 Color:', accent8);
    }, 100);
  }, []);

  return (
    <div>
      <p>Color of Accent 7: {accent7Color}</p>
      <p>Color of Accent 8: {accent8Color}</p>
    </div>
  );
};

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

Storing user-submitted files like images, PDFs, and PNGs into a database using ReactJS

I am currently in the process of developing an application that allows users to easily share files with each other by uploading them to their profiles. In order to achieve this, I have created a component called AddReport which sets up initial states for ...

Script for automated functions

I have implemented 4 functions to handle button clicks and div transitions. The goal is to hide certain divs and show one specific div when a button is clicked. Additionally, the background of the button should change upon hovering over it. Now, I am look ...

Just built a React App including a blog functionality, but for some reason the blog posts are not showing up. Any suggestions on how to fix this issue

I'm currently working on a project that involves creating a blog page for our react app. Despite my efforts, I am facing difficulty in getting the blog posts to show up. In order to retrieve all the posts from my MYSQL database, I have set up an API ...

Grunt integration for version control

After sticking to simple Html and Css for the longest time, I'm finally diving into JavaScript for a new project where I want to automate versioning. I've been following the SemVer Guidelines and my projects are currently versioned as "version": ...

"Encountering an error in Vue.js when trying to dynamically access nested arrays: push function not

My goal is to have two buttons displayed when a user uploads data: one for old products and one for new products. When the user clicks on either button, the corresponding products will be uploaded as 'old_product' or 'new_product'. Howe ...

React JS is not allowing me to enter any text into the input fields despite my attempts to remove the value props

Currently, I am working on creating a Contact Form using React Js. I have utilized react bootstrap to build the component, but unfortunately, when attempting to type in the input fields, the text does not change at all. import React, {useState} from ' ...

Attempting to utilize the LLL algorithm as described on Wikipedia has led to encountering significant challenges

I'm struggling with determining whether my issue stems from programming or understanding the LLL algorithm mentioned on Wikipedia. To gain a better understanding of the LLL algorithm, I attempted to implement it following the instructions outlined on ...

tips for positioning images and text in the center using css classes

Here's what I currently have: http://jsfiddle.net/nCs88/ Here's my goal: As a beginner, I am struggling to center the button images with the text. Any help would be greatly appreciated as this has been frustrating me for hours. ...

Ensure that the dimensions of a div remain consistent across all screen resolutions, specifically for desktops and not mobile devices

Currently I am in the process of creating a highly secure and encrypted social network, but I have hit a stumbling block. I hadn't considered how my website would display on other desktops and laptops (not mobile devices). The issue is that I set all ...

Determining the type of <this> in an Object extension method using TypeScript

I am attempting to incorporate a functionality similar to the let scope function found in Kotlin into TypeScript. My current strategy involves using declaration merging with the Object interface. While this approach generally works, I find myself missing ...

Loading textures locally using three.js is functioning properly, however, remote loading is not functioning as

I have customized an official example for the Loader object to showcase a specific issue. My goal is to generate a mesh with a texture map that loads before creating the geometry. Currently, I am facing a problem where local files load properly, but remote ...

Tips for reusing a form within a one-page website

I am looking for a way to handle a form's submit action using JavaScript. My goal is to hide the form when it is submitted and then be able to reuse it later. However, the code I currently have seems to have a hidden state that prevents the submit act ...

I am experiencing slow load times for my Angular 2 app when first-time users access it, and I am seeking assistance in optimizing its speed

Below, you'll find a snippet from my app.ts file. I'm currently working with angular2, firebase, and typescript. I'm curious if the sluggish performance is due to the abundance of routes and injected files? The application functions smoot ...

What is the best way to resize SVG graphics effectively?

I am in need of creating a seating chart. I have generated an SVG with the seats. <div class="seats-map"> <svg xmlns="https://www.w3.org/2000/svg" id="seats-map-svg" viewBox="0 0 1000 300"> <g data-row ...

What are the steps to applying strike-through text in Vue.js?

I am currently working on a to-do application using Vue.js and I want to implement a feature where the text rendered in HTML has a line through it when the user checks an item off the list. Here is the snippet of my code: <html> <head> & ...

Exploring the powerful capabilities of utilizing state variables within styled components

I'm attempting to create a button that changes its state based on the value of a property within an object. Below is the styled component const Btn = styled.button` border-radius: ${props => props.theme.radius}; padding:5px 10px; backgroun ...

The conversion to ObjectId was unsuccessful for the user ID

I'm looking to develop a feature where every time a user creates a new thread post, it will be linked to the User model by adding the newly created thread's ID to the threads array of the user. However, I'm running into an issue when trying ...

I can't seem to figure out why the removeChild() function is not functioning properly in my

Recently, I've been working on a search website where users can input either a partial or full name and then click a button to display a list of actors whose names contain that specific string in a hint-like fashion. These names are sourced from a MyS ...

Utilize AngularJs and JavaScript to upload information to a JSON file

Exploring the realm of Angular JS, I am on a quest to create a CRUD form using AngularJs and Json with pure javascript without involving any other server side language. The script seems to be functioning well but is facing an obstacle when it comes to writ ...

Problem with jQuery image gallery

Currently, I am in the process of creating a simple image gallery that enlarges an image when it is clicked. To achieve this functionality, I am utilizing jQuery to add and remove classes dynamically. $(".image").click(function() { $(this).addClass("b ...