'Framer Motion React - Creating a image carousel and when I resize the dom the the dragContraints no longer work

I was hoping to get your help with a problem I have been having with useRef, and Framer motion.

I currently am creating a carousel component for featured items that could have any amount of slides depending what the user tags.

The problem I am having is when the dom is resized the ref is no longer calculating the right drag contraints and I am not able to scroll the full list on the X-Axis.

Here is the code

import { motion } from 'framer-motion';

import SliderStyles from './Slider.module.scss';
import Button from '@components/buttons/Button';

type SliderProps = {
  images: string[];
};

const Slider = ({ images }) => {
  const sliderRef = useRef(null);
  const [width, setWidth] = useState(0);

  useEffect(() => {
    if (sliderRef.current) {
      const { clientWidth, scrollWidth } = sliderRef.current;
      setWidth(-(scrollWidth - clientWidth));
    }
  }, []);

  return (
    <motion.div className={SliderStyles.Slider} ref={sliderRef}>
      <motion.div
        className={SliderStyles.SliderTrack}
        drag="x"
        dragConstraints={{
          right: 0,
          left: width - 50,
        }}
      >
        {images.map((image, index) => (
          <div
            className={SliderStyles.SliderItem}
            key={image + index.toString()}
          >
            <div className={SliderStyles.SliderOverlay}>
              <h3>Product Name</h3>
              <Button type="button">Order Now</Button>
            </div>
            <img src={image} alt="slider item" />
          </div>
        ))}
      </motion.div>
    </motion.div>
  );
};

export default Slider;

Thanks in advance, any help is appreciated!



Solution 1:[1]

https://github.com/framer/motion/issues/1454#issuecomment-1073807017

temporary solution found in github issues - Follow the link above if you run into this issue as well!

Hopefully a fix is made in newer releases

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alan-eMartin