0

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 !

Peter Malik
  • 403
  • 4
  • 14

1 Answers1

2

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"}}
>
Guillaume Brunerie
  • 4,676
  • 3
  • 24
  • 32