LittleMonkey20
LittleMonkey20

Reputation: 77

Create responsive image display in React

I'm new to frontend, react and have a question on display responsive images.

Inside a React component, I have fetched some image info from an API endpoint and stored them inside a React.useRef in order to display them in a carousel. Like:

const carouselItem = React.useRef<Array<ImageTypeA>>([]);

apiResponse.forEach((image) => {
    carouselItem.current.push({
        images: (
            <img
                id={`${image.title}`}
                src={image.imageUrl}
        ),
    });
});

But there are two different sizes of carousels I need to display in the same component with the same set of images (In this case carouselItem).

For the two carousels, I want to display a smaller set of images and a larger set of images. And they should display according to the size of the screen (responsive).

const CarouselDiv1 = styled.div`
    img: [];
`;

const CarouselDiv2 = styled.div`
    img: [];
`;

... return method

return (
   <div>
       <CarouselDiv1>
       // display smaller image carousel
       </CarouselDiv1>

       <CarouselDiv2>
       // display larger image carousel
       </CarouselDiv2>
    </div>
)

I'm thinking of creating two styled components for each carousel and displaying them inside the return function. But I'm not sure how to do it or is there a better way to do it? Thanks

Upvotes: 0

Views: 714

Answers (1)

szgezu
szgezu

Reputation: 68

You can do something like this.

export default function App() {
  const [isDesktop, setDesktop] = useState(window.innerWidth > 500);

  const updateMedia = () => {
    console.log(window.innerWidth);
    setDesktop(window.innerWidth > 500);
  };

  useEffect(() => {
    window.addEventListener("resize", updateMedia);

    return () => window.removeEventListener("resize", updateMedia);
  });

  return (
    <div>
      {isDesktop ? (
        <div>higher then 500px</div>
      ) : (
        <div>lower then 500px</div>
      )}
    </div>
  );
}

Or you can use the React-responsive package.
https://www.npmjs.com/package/react-responsive

Upvotes: 1

Related Questions