This question was asked before but was never fully answered in textThe variables are probably the most important part of this code as I want to be able to use them in multiple CSS functions to animate them with hover effects. I have the html equivalent which is this
<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 want my code to be able to do the same thing in a React inline style JSX/JS file. So far all I’ve come to is 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 unfortunately only uses the last value in the list (being 1) and uses this value for all functions in the CSS file.
2
Answers
Based on the link you posted, I think what you’re trying to achieve is setting a CSS variable in the
style
prop for a JSX Element.You can do so like this:
I created a Code Sandbox that shows this in action where the value for
--i
comes from some array of whatever length. The--i
value is then used as a part of the background color and transform CSS props for a div. The screenshot below shows the resulting UI for an array of 20.Note: This example uses Material UI so you won’t be able to
copy/paste
from the Code Sandbox. You will have to change thesx
prop tostyle
if you want to reuse the code.Hope this helps!
Test this: