maxmarinich / react-alice-carousel

React responsive component for building content galleries, content rotators and any React carousels
MIT License
832 stars 91 forks source link

force update or similar ? #291

Closed bogdancss closed 1 year ago

bogdancss commented 1 year ago

Looking for a way to force update the carousel as items are added/removed from it.

maxmarinich commented 1 year ago

Hi, @bogdancss! The force update is antipattern. Pass items like props & carousel will updates automatically when the props will updated.
The most similar to force update behavior occurs when using the renderKey property:

import React, { useState, useEffect } from 'react';
import AliceCarousel from 'react-alice-carousel';
import 'react-alice-carousel/lib/alice-carousel.css';

const src = (name = '') => `//github.com/maxmarinich/react-alice-carousel/raw/master/src/assets/img/${name}`;

const Carousel = () => {
    const [key, setKey] = useState(0);

    const [items] = useState([
        <img src={src('1200x200.jpg')} key="0" />,
        <img src={src('1200x250.jpg')} key="1" />,
        <img src={src('1200x300.jpg')} key="2" />,
    ]);

    // call this function to force update
    function updateRenderKey() {
        setKey(Date.now());
    }

    return (
      <AliceCarousel renderKey={key} items={items} />
    );
};
bogdancss commented 1 year ago

OK - this makes sense.

Is there a way to have an onUpdate method? I need to know the itemsInSlide after I add new items to the carousel.

I set this to a visibileItems state through the onInitialise and onResize methods, but I'd need it on and onUpdate as well

@maxmarinich