brainhubeu / react-carousel

A pure extendable React carousel, powered by Brainhub (craftsmen who ❤️ JS)
https://brainhub.eu/
MIT License
1.07k stars 165 forks source link

Remove the current Images from Carosel and load a new set of images. #663

Open chauchinyiu opened 3 years ago

chauchinyiu commented 3 years ago

Hello, I try to load different set of images in the carousel, however when i load a new set of images. the previous set of images is always there. i have to click the arrow button in order to show the new set of images in the carousel. the following code is my code. Is there any function to make carousel to remove all the images? Thanks for your attention

const [slideImages, setSlideImages] = useState([])

function loadImages(){
        setSlideImages([]); //<----  do not remove all the images from the carousel 
        if (props === undefined) {return}
        fetch(imageUrl)
        .then(res => res.json())
        .then((data) => {
          let images = data.results
          var imagesInstance = [];   
          for(var i=0;i<images.length; i++){  
            imagesInstance[i] = images[i]      
          }
          setSlideImages(getRandomArrayElements(imagesInstance, 10))      
        })
        .catch(console.log)
     }

 return (
            <Carousel className="carosel"
            plugins={[
                'centered',
                'infinite',
                'arrows',
                {
                    resolve: slidesToShowPlugin,
                    options: {
                        numberOfSlides: 2,
                    },    
                },
                {
                    resolve: slidesToScrollPlugin,
                    options: {
                        numberOfSlides: 2,
                    },
                },

            ]}   
            >
           {slideImages.map((each, index) => (
              <div key={index} className="each-slide">
                <img className="lazy" src={each} alt={props.english} />
              </div>
            ))}
            </Carousel>

    );
krehwell commented 2 years ago

I think re-rendering the carousel will do the trick.

when you received the new images, trigger a state to re-render the carousel

const [reRender, setReRender] = useState(false);

const getNewImage = () => {
    ... // received new images
    setReRender(true); // trigger re-render once new images received
}

useEffect(() => {
    if (reRender) {
        setReRender(false) // we just want to re-render the carousel. So, when `reRender` value is true we set it back directly to false again.
    }
}, [reRender]);

return (!reRender && <Carousel .../>)