Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Component does not reflect CSS style changes

I got a problem with a React component that takes as a prop scrollY:

const Button = ({
    scrollY,
}) => {

    const [localScrollY, setLocalScrollY] = useState(0);

    useEffect(() => {
        setLocalScrollY(scrollY);
    }, [scrollY]);

    console.log(`mt-[${localScrollY}px]`);

    return (
        <motion.button
            className={`top-3 mt-[${scrollY}px] ....`}
        >
           ......
        </motion.button>)

I can see the mt class change in the console when scrolling , yet it does not reflect in the UI.Additionally , the console.log shows the expected class. Could you please let me know what I might be doing wrong ?

Thank you !

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You cannot use dynamic class names like mt-[${scrollY}px] in tailwind, as all the class are statically generated at compile time. If you need a CSS property to depend on a truly dynamic value like a scroll amount, you should use inline styles for it:

<motion.button
  className={`top-3 ....`}
  style={{marginTop: scrollY + "px"}}
>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading