What is the reason for my difficulty in dynamically updating CSS values with variables in ReactJS?

Today I decided to experiment with updating CSS values using CSS variables for the first time. Unfortunately, I encountered an issue where the previous value did not change despite my efforts. Here is the snippet of code I used:

CSS variable declaration

:root {
--tx: -0%;
}

.move{ 
 transform: translateX(var(--tx));
}

In my React project, I utilized a useState hook and initially set it to a value of -33 for testing purposes.

 const [movePosition, setMovePosition] = useState(-33);

I then proceeded to create a function to update the CSS variable based on the current value stored in the movePosition state.

const handleNextSlide = ()=>{
  setSlider1(slider1 + 1);
  setSlider2(slider2 + 1);
  setSlider3(slider3 + 1);
 getComputedStyle(document.documentElement).getPropertyValue('--tx', 
 `${movePosition}%`);
 }

To trigger this function, I added a button that listens for the onClick event.

 <MdNavigateNext onClick={handleNextSlide}/>

Despite all my efforts, clicking the button did not result in the CSS values changing to the desired movePosition state value of -33. Even hard coding it did not yield the expected outcome. Any suggestions on how to resolve this issue?

Answer №1

If you're using ReactJS, it's possible to dynamically update CSS variables by enclosing them in a string

<MdNavigateNext onClick={handleNextSlide} style={{'--tx':`${movePosition}%`}}/>

Answer №2

To effectively update CSS variables, use the following API:

const handleNextSlide = ()=>{
  setSlider1(slider1 + 1);
  setSlider2(slider2 + 1);
  setSlider3(slider3 + 1);
  document.documentElement.style.setProperty('--tx', `${movePosition}%`);
}

More information can be found at: https://css-tricks.com/updating-a-css-variable-with-javascript/

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

Setting multiple positions for jQueryUI tooltips based on specific classes

I recently followed these instructions on utilizing jQueryUI tooltip to load content via ajax. (fiddle)(Full Screen). However, I encountered an issue where I'm unable to set a different position for the second tooltip (`.loadtip`) compared to the firs ...

Arranging identical elements with a comma in between

My xquery is designed for a collection of books that have multiple topics associated with each one. When I run the query, all the topics are grouped together in one cell of the table (which is what I want), but they are difficult to separate. let $books : ...

A guide on retrieving information from a database with PHP and transferring it to Javascript

As I work on creating a website using HTML, CSS, MySQL, and JavaScript, my goal is to allow users to log in and engage in a quiz with 40 questions. Below is the JavaScript code for a countdown timer that includes the "questions" variable. After 40 seconds ...

Ways to dynamically update a div with data from a JSON response

I'm currently in the process of developing a search platform. I have three static divs on the search results page that display certain content, all containing similar code. For example: <div id="result" class="card"> <img src="hello.png" ...

`The challenge of a single web page not displaying correctly`

I was working on a website for a local computer building company, and I decided to make it a single-page applet. The HTML is mostly done, and I don't have much trouble with CSS. However, I encountered an issue with hiding and displaying different sect ...

Struggling with properly configuring and deploying create-react-app with NPM?

I've been exploring the Node ecosystem and attempting to establish continuous deployment for my application on AWS Amplify. My project structure is as follows: project public index.html src App.tsx/App.js package.json This structure wa ...

Following the content update via Ajax, the functionality of jQuery is experiencing glitches

My content slider works well on the first page of ajax loaded content. However, when I navigate to the next page from ajax loaded content and try to update the sliding animation for newly loaded future content using #readyslider, the slider starts glitchin ...

The has class method is failing to work within the if statement

I have encountered an issue with my Accordion code. When I test it, the word 'not' is displayed twice, while 'hve' is not displayed at all. $('.st-accordion li a').click(function() { if ($(this).parent().not('activeac ...

Troubleshooting problems with React Hook Form Controller

Hey there, I'm currently working on creating a form using react-hook-form and material-ui. I want to avoid writing Controller every time for all TextFields, so I decided to declare it in another file and call it in my form. However, I'm facing is ...

The element in TS 7023 is implicitly assigned an 'any' type due to the fact that an expression of type 'any' is not valid for indexing in type '{}'

I have implemented a select-box that includes options, labels, optgroups, and values. Is my approach correct or is there something wrong with the way I have defined my types? interface Option { label: string value: string selected?:boolean mainGrou ...

Having Trouble with Form Submission in React with Formik and Yup

I'm currently utilizing the Autocomplete component from Material UI along with Formik and Yup for validation purposes. The issue I am facing is that upon submitting my values and checking the console, nothing appears, indicating a failure to meet the ...

Ways to emphasize an HTML table column without the need for loops

I am facing a situation where I have a table structured as follows: <table> <thead> <tr> <th id="col-1"><input type="button" class="some" value="Company" /></th> <th>name</th> <th> ...

Error message: When the mouse hovers over, display the chart(.js) results in TypeError: t is

I encountered a persistent error that I just can't seem to resolve. My goal is to showcase a chart using Chart.js when the mouse hovers over the canvas. However, upon hovering over the canvas, I keep getting a TypeError: t is null error. Error: { ...

JavaScript is abstaining from generating a div element

I've been struggling for the last couple of hours to create a special div element with specific properties, but no matter what I try, it just won't work. Can someone please point out where I'm going wrong? function generateRoundDiv() { var ...

Concealing a CSS class with PHP within the Wordpress Woocommerce platform

I have very limited knowledge in programming and need help with a code snippet. I am using the Wordpress Snippets Plugin to hide the Add Cart Button from a single product. add_action( 'wp', 'rudr_remove_add_to_cart_single_product' ); fu ...

Exploring the capabilities of Next.js by implementing dynamic and nested routing

In my React App, I've set up the following routes: <Route path="/blog" element={< Blog />} /> <Route path="/blog/:slug" element={<BlogPost />} /> <Route path="/blog/search" element={<Blog pag ...

Unable to accommodate data within the fixed width confines of the GridView cell

I am having a column in my table with lengthy text that requires scrolling to see the end. Is there a way to adjust the content to fit within a fixed-width cell? Here is the UI setup for the GridView: <asp:GridView ID="GridView1" runat="server" OnPag ...

In the Astro framework, React components are unable to access the window object

I am currently utilizing preact in my Astro project and everything was working smoothly until I added 'window'. ReferenceError: window is not defined Despite the fact that Astro does server-side rendering, in this scenario, it involves a React c ...

What is the reason for the child component having a greater number of props compared to the parent component

I am facing an issue with my parent component and child component in React. The child component seems to have more props data than the parent component. Parent component: import React, { Component} from 'react'; import { Link } from 'react ...

Looking for a uncomplicated yet robust JavaScript text editor that generates uniform tags?

I am currently working on a web application that enables users to create and store a personalized "about me" section. To simplify the process, I am looking for a JavaScript-based editor that includes standard formatting options like bold, italic, underline ...