Felipe César
Felipe César

Reputation: 1444

How to make a responsive number os slides in a react carousel

I have a React Carousel that shows 3 elements at once. I would like to adjust this number of elements according to the size available. So for example

const RCarousel = ({items}) => {
  const numItems = 3;

  return (
    <Carousel
      numItemsPerView={numItems}
    >
      {
        items.map(
          (item) => <Item item={item} />
        )
      }
    </Carousel>
  )
}

I would like to change numItems to 2 if the RCarousel size is tablet size and 1 if is mobile size.

RCarousel may have a different width of the window width. Any suggestions how to make this? :)

Upvotes: 0

Views: 655

Answers (2)

Felipe C&#233;sar
Felipe C&#233;sar

Reputation: 1444

Improving @szczocik's answer I was able to solve it using the following:

created a hook to get window size

useWindow.size.js

import {useState, useEffect} from 'react'

const useWindowSize = () => {
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  });

  useEffect(() => {
    if (typeof window === 'undefined') return; //specific for gatsby or applications using webpack
    
    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }
    
    window.addEventListener("resize", handleResize);
    
    handleResize();
    
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return windowSize;
}

export default useWindowSize;

mycomponent.js

  const windowSize = useWindowSize();

  useEffect(() => {
    const width = windowSize.width;

    if (width >= 1200) {
      if (numItems !== 3) {
       setNumItems(3);
      }
    } else if (width > 900) {
      if (numItems !== 2) {
        setNumItems(2);
      }
    } else {
      if (numItems !== 1) {
        setNumItems(1);
      }
    }
  }, windowSize)

Upvotes: 2

szczocik
szczocik

Reputation: 1343

You can use window.innerWidth and window.innerHight to get the size of the window. Once you have the sizes, you can conditionally change it. I would stick the numItems in the useState and use useEffect to change it. Something along those lines

const [numItems, setNumItems] = useState(3);
const width = window.width;
useEffect(() => {
    if (width > 800) {
        setNumItems(3);
    } else {
        setNumItems(1);
    }
}, [width])

Upvotes: 2

Related Questions