What is the correct syntax for utilizing a variable in inline styles within ReactJS, specifically when working with the --i:0

           

The question has been raised previously, but unfortunately, it was left unanswered in this thread. The variables play a crucial role in this piece of code as they are intended to be utilized in various CSS functions for animating them with hover effects. Here is the equivalent HTML:


<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>
<body>
  <div class="container">
    <div class="card" style="--i:-1" ></div>
    <div class="card" style="--i:0"></div>
    <div class="card" style="--i:1"></div>
  </div>
</body>
</html>

export default Project

I aim to achieve the same functionality within a React inline style JSX/JS file. Thus far, my attempt looks like this:

import './project.css';
const numbers = [-1, 0, 1]
var r = document.querySelector(':root');
const Project = () => {
  return(
    <html lang="en">
    <head>
      <meta charSet="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Document</title>
    </head>
    <body>
      <div className="container">
      {numbers.map((num) => (<div key={num} className="card" {...r.style.setProperty('--i', -1)}></div>))}

      </div>
    </body>
    </html>
  )
}

export default Project

However, this approach unfortunately only takes the final value from the list (which is 1) and applies it across all functions in the CSS file.

    

Answer №1

Here's a sample test:

       <html>
        <div class="container">
          {items.map((item) => (
            <div key={item} class="box" style={{ "--index": item }}></div>
          ))}
        </div>
      </html>

Answer №2

After reviewing the link you shared, it seems like your goal is to set a CSS variable in the style property for a JSX element.

This can be achieved by following this example:

const SomeComponent = () => (
  <div 
    style={{
      "--i": -1
    }}
  >
    <div
      style={{
        // rotating based on an arbitrary calculation using the `--i` CSS variable
        transform: "rotate(calc(360deg / 8 * (var(--i) - 10)))",
        width: "100px",
        height: "100px",
        backgroundColor: "magenta"
      }}
    />
  </div>
)

I have also provided a demonstration of this concept in action through a Code Sandbox. In this example, the value for --i is extracted from an array of varying lengths and utilized in setting the background color and transformation properties of a div. You can see the resulting interface below for an array size of 20.

Kindly note that this implementation utilizes Material UI, which prohibits direct copying from the Code Sandbox. If you wish to reuse the code, remember to replace the sx property with style.

I trust this explanation proves helpful!

https://i.sstatic.net/E8Mpx.png

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

Determine the vertical distance that a div element is currently visible while scrolling

To better understand this concept, please refer to the following fiddle: http://jsfiddle.net/abhicodes/LasxP/ The main goal here is to calculate the visible height of the element with the ID #content-wrapper as the user scrolls. The height of the header ( ...

What is the best technique for creating a preloader that can seamlessly fill the background of a vector image?

I am looking for guidance on creating a CSS3 preloader using a vector image. My goal is to have the logo start off transparent with only the border visible, and as the loading occurs, fill in from bottom to top with the background color. Thank you to ever ...

Tips for updating the border color of a button:

Struggling to alter the border color of a button Attempting borderColor attribute proved futile: borderColor: '#FFFFFF' Anticipated result Code snippet: headerBtn: { backgroundColor: 'black', fontSize: '16px', f ...

Asynchronous data fetching adding two entries to an array

I've been experimenting with making API calls for Rick & Morty using fetch and async arrow functions, but I've run into an issue where the elements are being added to my array twice. I've tried calling the function both with and without useE ...

The Ant Design form.setFieldsValue method does not trigger a re-render when a Form.Item contains multiple elements

Struggling to update a Cascader field value using an "onClick" event within a Form.Item element in the Antd Form Component. It seems that the issue lies in the inability of Form.Item to update the field value when there are multiple elements inside the ta ...

Implementing a Create-React-App with Rails API integration on Heroku platform

I'm encountering an issue with deploying my react/rails app on Heroku. Although I've successfully deployed it and the rails server is running, the react app itself is not displaying. It seems like I'm very close to resolving the issue but I ...

Organize data in a Vue.js table

Currently facing an issue with sorting my table in vue.js. Looking to organize the table so that campaigns with the highest spend are displayed at the top in descending order. Here is the code I'm working with: <template> <div class=" ...

Retrieve various profiles based on the props condition in React

Within my application, users log in using their unique user ID. Once logged in, the app redirects them to their profile, which is fetched using a specified API. Each user has different authorization keys required to perform the fetch. My goal is to dynamic ...

Troubleshooting sequential image loading in KineticJS and resolving issues with opacity tween when setting fillPatternImg

In my latest project using KineticJS, I am developing a small app that generates multiple nodes in the form of RegularPolygons. Once the stage has loaded (activated with play();), I proceed to sequentially fill each node with an image pattern using loadIma ...

The HTML <select> element is currently styled with a locked CSS, but I am looking to have it displayed with the default

Unfortunately, I am unable to make changes to the CSS file at this time. The current styles in the CSS file are as follows: font-size: 13px; padding: 6px 4px; background-color: rgb(238, 238, 238); border: 1px solid rgb(204, 204, 204); clear: both; margin- ...

What is the best way to retrieve data from a POST request?

I am attempting to post data from the same site and create a new order when the submit button is clicked. However, I am not receiving any information in my req.body, leading me to suspect that there may be an issue with my ejs file. Any feedback on this ma ...

Trouble with displaying events on Angular UI-Calendar

I've been working with Angular UI Calendar and following the steps outlined on their website: http://angular-ui.github.io/ui-calendar/ Despite implementing everything correctly, I'm facing an issue where the events fetched from my API are not s ...

Developing with Phonegap Build: A Guided Process

With all the conflicting information available, I am seeking clarity on this topic. Objective: To create and enhance a Phonegap app using Phonegap Build. 1) My preference is to utilize Phonegap Build without needing to install Android and iOS SDKs. 2) I ...

I'm looking for assistance on how to set the minimum height using jQuery. Can anyone provide

My attempt to use the minHeight property in one of my divs is not successful, and I am unsure why... <div id="countries"> <div class="fixed"> <div class="country" style="marging-left:0px;"></div> <div class="country"&g ...

Enhance the appearance of an HTML select tag for optimal viewing on iOS Safari browser for

I have customized three dropdown lists using CSS. I set the style as follows: .dropdown{ font-size: 20px; background: white; border:none; position: relative; } While the dropdowns appear fine in Chrome, there seems to be a slight differen ...

Achieving CSS transition effects using the .appendChild function in JavaScript

When using the mouseenter event, I have a JavaScript function applied to an svg path element: const fadeIn = (event, locale) => { event.target.style.fill = 'hwb(' + (120 - score[locale] * 1.2) + ' 0% 0% / 1)' } This function wor ...

Tips for testing the setTimeout function within the ngOnInit using Jasmine

Could someone please assist me with writing a test for an ngOnInit function that includes a setTimeout() call? I am new to jasmine test cases and unsure of the correct approach. Any guidance would be greatly appreciated. app.component.ts: ngOnInit(): void ...

What is the best way to securely transfer API keys to a React frontend for use in a React component?

I'm currently working with @react-google-maps/api to develop a map component in React. To load the component, we have to provide an API key for useJsApiLoader. How can I securely manage the API key so it's not exposed on the frontend? (Using an E ...

What is the best way to vertically align the second row in a carousel using Tailwind CSS?

Currently, I am working on developing an up-and-down carousel with Tailwind CSS. However, I am encountering a challenge in aligning the elements in the second row of my grid. My main objective is to have these elements centered vertically within the grid. ...

BookshelfJS: Establishing a One-to-One Relationship

Within my database, I am working with two tables - User and Address. The User table consists of the following two methods: shippingAddress: function() { var Address = require(appRoot + '/config/db').model('Address'); return thi ...