I'm trying to create an animation effect where the width of a button changes whenever the text inside it is updated. I've attempted using useRef on the button itself to grab its clientWidth and then applying that value to a CSS variable in order to adjust the width dynamically.
However, I'm encountering an issue where although the width is being set correctly, the animation isn't working as expected. Strangely, if I manually adjust the width in Chrome Developer Tools, the animation works fine. But when I revert back to using the CSS variable and update the inner text, the animation fails to trigger.
.button {
width: var(--buttonwidth);
transition: width 2s ease-in-out;
}
// Update css variable when button text changes
useEffect(() => {
const buttonInnerWidth = buttonRef.current.clientWidth;
document.documentElement.style.setProperty(
'--buttonWidth',
`${buttonInnerWidth}px`
);
console.log(buttonInnerWidth);
}, [children]);
Does anyone have a more effective solution to achieve this animation effect?