I am trying to achieve a rolling y-axis list which I successfully coded. Here is the behaviour.
I’m working on a React component where I dynamically apply Tailwind CSS classes based on a prop (deviceWidth
). The problem is that on the first render, the component does not apply the desired styles. However, if I hardcode the values and then switch back to the dynamic approach, the styles apply correctly.
import React, { useState, useEffect, useRef } from 'react';
function Hero(props) {
const [currentIndex, setCurrentIndex] = useState(40);
const myRef = useRef(null);
useEffect(() => {
const element = myRef.current;
let intervalId;
const updateScroll = () => {
if (currentIndex <= 160) {
setCurrentIndex(prevIndex => prevIndex + 40);
element.scroll({ top: currentIndex, behavior: 'smooth' });
} else {
setCurrentIndex(0);
element.scroll({ top: currentIndex, behavior: 'smooth' });
}
};
intervalId = setInterval(updateScroll, 1000);
return () => clearInterval(intervalId);
}, [currentIndex]);
const roles = ["Title 1", "Title 2", "Title 3", "Title 4"];
const sizing = {
"sm" : {
h: "2",
t: "4"
},
"md" :{
h: "4",
t: "5"
},
"lg" :{
h: "6",
t: "6"
}
};
const deviceSizing = sizing[props.deviceWidth] || sizing.sm;
return (
<header className="mt-6 flex flex-col">
<div className="text-center text-4xl font-semibold">I'm</div>
<div className={`m-2 h-${deviceSizing.h} snap-y snap-mandatory overflow-y-hidden text-center text-${deviceSizing.t}xl font-semibold`} ref={myRef}>
{roles.map(item => (
<div key={item} className="mb-2 snap-center underline decoration-green-500">{item}</div>
))}
</div>
</header>
);
}
export default Hero;
Steps to Reproduce:
-
Create a React component that uses dynamic Tailwind CSS classes based on a prop.
-
Pass different values to the prop (
deviceWidth
) and observe the initial render. -
Notice that the styles are not applied correctly on the first render.
What I’ve Tried:
-
Hardcoding the values instead of using the dynamic approach works.
-
Switching back to dynamic values after hardcoding seems to fix the issue temporarily.
Question: How can I ensure that Tailwind CSS applies the dynamic classes correctly on the initial render?
Additional Information:
-
I’m using Tailwind CSS with JIT mode enabled.
-
The issue occurs regardless of the value passed to
deviceWidth
(e.g., “sm”, “md”, “lg”).
Any help or suggestions on how to resolve this issue would be greatly appreciated!