Hi,
I've built a component which lays out a number of buttons from an Array that is passed in as a prop and there is a marker that animates to highlight which button is pressed. State is handled by the parent component. I can see animation but each time I press a button it starts from 0px rather than animating from its current position.
I'm sure this is a fairly basic error that I'm doing but having read the docs I'm struggling.
Could some kind soul please take a look and see where the error might be in my code? I'd be very grateful.
Here is the child component code
import { gsap } from "gsap";
import PropTypes from "prop-types";
import { useLayoutEffect, useRef } from "react";
function SlideToggle({ buttonArray, handleClick, currentIndex }) {
const sendValueToParent = (value) => {
handleClick(value);
};
// gsap code for toggle marker
const component = useRef(null);
useLayoutEffect(() => {
let ctx = gsap.context(() => {
gsap.to(".slide-marker", {
x: currentIndex * 40,
duration: 0.5,
});
}, component);
return () => ctx.revert(); // cleanup!
}, [currentIndex]);
const buttonElements = buttonArray.map((el, index) => (
<button
className="w-[30px] h-[30px] flex justify-center items-center text-white"
key={index}
onClick={() => sendValueToParent(index)}
>
{el.icon}
</button>
));
return (
<div className="relative" ref={component}>
<div className="slide-marker w-[30px] h-[30px] absolute bg-white bg-opacity-10 top-0 pointer-events-none"></div>
<div className="flex space-x-[10px]">{buttonElements}</div>
</div>
);
}
export default SlideToggle;
SlideToggle.propTypes = {
buttonArray: PropTypes.array,
handleClick: PropTypes.func,
currentIndex: PropTypes.number,
};