Guide to creating a dynamic amount of slides in a React carousel for optimal responsiveness

Looking for a solution to adjust the number of elements displayed in my React Carousel based on available size? I have a React Carousel that currently shows 3 elements at one time. Here is the code snippet:

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

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

I am interested in changing the value of numItems to 2 when the RCarousel is at "tablet size", and to 1 when it is at "mobile size". However, given that RCarousel's width may vary depending on the window size, any advice on how to achieve this dynamically? :)

Answer №1

To determine the window size, you can utilize window.innerWidth and window.innerHight in your code. Once you have obtained the dimensions, you can dynamically adjust them. One suggestion is to store the number of items in a state variable using useState and employ useEffect for updating it based on certain conditions.

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

Answer №2

Enhancing @szczocik's solution, I managed to resolve it by implementing the following steps:

Established a custom hook for fetching window dimensions

windowSize.js

import {useState, useEffect} from 'react'

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

  useEffect(() => {
    if (typeof window === 'undefined') return; //specifically designed for Gatsby or webpack-based applications
    
    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)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A pair of buttons and text with varying alignment

Here is the code from my popup.htlm file: HTML <body> <select style="width: 100%;" multiple id="HLSlist"> </select> <span style="display:inline"> <button type="button" id="Deletebut">Delete</button> ...

Is it feasible to create a doughnut chart with curved edges?

My goal is to create a doughnut chart, but my search for reliable CSS/SVG/Canvas solutions has not been successful. https://i.sstatic.net/Rq6Lx.jpg I want each segment to have fully rounded corners, which presents a unique challenge. ...

I am able to see the Redux props showing up in Redux DevTools, but for some reason they are not

I am facing an issue where I am passing a Redux prop to a component that is fetched from a payload. The payload successfully updates the state in my reducer and the component receives the prop (an array of objects fetched in the action) according to my Red ...

Encountering an issue when retrieving data in a React component with the getStatic

Having trouble fetching data in my Next.js project using the getStaticProps() function, I keep encountering this error message: TypeError: Cannot read property 'map' of undefined The code snippet causing issues is as follows: export const getS ...

jQuery-powered responsive layout with three columns

I am currently working on creating a dynamic three-column layout that allows users to resize the columns in their browser. Using jQuery for column resizing, I have successfully adjusted the first two columns but am encountering difficulties with the final ...

Tips for customizing MuiInputLabel outlined in mui 5

I am in the process of transitioning from material-ui 4 to mui 5 and I am looking to customize MuiInputLabel using theme overrides. So far, here is what I have attempted: 'MuiInputLabel': { 'styleOverrides': { 'marginDense&a ...

NextJs is leading the way with its fantastic PWA support

Our goal is to create a react web application that can function fully offline. Typically, we utilize NextJS for our projects. We are currently facing an issue where we are unable to precache all routes of the application, even if they do not use server-si ...

Rendering ReactJs on the server side versus the client side

I'm utilizing react-router for managing both server-side rendering and client-side rendering in my React application. However, I've noticed that the entry point of my app contains the following code: Router.run(routes, Router.HistoryLocat ...

Personalizing CSS classes in ASP.NET

In the project I'm currently developing, users will have the ability to customize the font color of header titles. These header titles are styled using values from a cssClass, which includes properties such as font-size, font-color, font-weight, and ...

Issue with nextjs not returning the updated object correctly

I'm currently developing a nextjs app that incorporates authentication. There are two key functions that I execute on each page load. The first function checks for the existence of jwt cookies and then calls another function to validate the tokens if ...

Testing Form with Select using Ant Design components and React Testing Library

I'm having trouble testing a customized Select input within an Ant Design Form that is pre-filled with initial values. The test is failing because the Select component is not receiving a value. What would be the best approach to properly test this "cu ...

Tips for activating multiple CSS animations when scrolling

I am currently working on a project that involves multiple CSS animations. However, I am facing an issue where these animations only occur once when the page initially loads. I would like them to trigger every time the user scrolls past them, regardless of ...

Best Practices for Organizing Enums in Your React Application

In my React project, I am working with multiple enums. How should I organize them within my application? Currently, I have created an enums.js file located in the config folder where I define enums as follows: export const USER_TYPES = { USER: "user", ...

Tips for concealing JavaScript files from the Chrome Developer Tools while using Next.js

Currently working on a project using Next.js. I've noticed that the utils/components are quite visible through the Chrome Developer Tools, as shown in this image: https://i.sstatic.net/jaLmg.png Is there a way to hide them from being easily accessib ...

The React modal window stubbornly refuses to close

import c from '../Profile.module.css'; import { useState } from 'react'; import { createPortal } from 'react-dom'; import Modal from '../Modal/Modal'; const TransactionItem = (props) => { const modalRoot = ...

How come the client directory from my project didn't get sent to GitHub?

When attempting to upload my project to a Github repository for the first time, I noticed that all folders' content was successfully uploaded except for the client folder. Strangely, the icon for this folder looks different compared to the others. Can ...

When you reach the end of the page, the loadMore function is triggered multiple times

On my webpage, I have a list of profiles that are displayed. When the user reaches the bottom of the page, more data should be loaded through the loadMore function. While the loadMore function itself works correctly, I am facing an issue with the listener. ...

Tips for preventing the state of a checkbox from being saved in the browsing history

I have implemented a mobile menu using a checkbox, with the following simplified code: input, ul { display: none; } label { cursor: pointer; } input:checked ~ ul { display: block; } <input type="checkbox" id="toggle-menu" /> <label for="t ...

Spacing within Material UI Grid List items

Exploring Material UI for the first time, I am looking to adjust the spacing between image tiles within the Grid List component. Despite consulting the Material UI documentation and scouring through various threads on Stack Overflow, I have yet to come a ...

What are the steps to integrate redux-form with material-ui version 1 (material-ui-next)?

I'm a huge fan of both projects, but this is my first time trying to integrate them. From what I understand, the only project that combines the two is redux-form-material-ui, which unfortunately isn't compatible with material-ui-next. Does anyon ...