yaodingyd / react-flickity-component

A React.js component for using @desandro's Flickity
314 stars 51 forks source link

imagesloaded needed on updates as well #83

Closed matthewlein closed 3 years ago

matthewlein commented 4 years ago

If you render a carousel, then replace children with new images, imagesloaded is not used, so new carousel will be sized incorrectly

In componentDidUpdate, I added an imagesLoaded to make sure the carousel sizes are recalculated with reloadCells. There are probably some optimizations to not run it on every update, but that's the gist of it. Maybe it should only run on children changes.

https://github.com/theolampert/react-flickity-component/blob/96a209e61e9b8152e17f5756441bd23b9baf2d79/src/index.js#L19-L39

  componentDidUpdate(prevProps, prevState) {
    const {
      children,
      options: { draggable, initialIndex },
      reloadOnUpdate,
    } = this.props;
    const { flickityReady } = this.state;
    if (reloadOnUpdate || (!prevState.flickityReady && flickityReady)) {
      this.flkty.deactivate();
      this.flkty.selectedIndex = initialIndex || 0;
      this.flkty.options.draggable =
        draggable === undefined
          ? children
            ? children.length > 1
            : false
          : draggable;
      this.flkty.activate();
// --- ADDED
      if (!disableImagesLoaded && this.carousel) {
        imagesloaded(this.carousel, () => {
          this.flkty.reloadCells();
        });
      }
// ---
    } else {
      this.flkty.reloadCells();
    }
  }
zurmoehle commented 4 years ago

This helped also with my problem. Please add this in the component. Is there a global fix without change the node_module itself?

matthewlein commented 4 years ago

In my case, I copied over the component to make more changes—typescript, only resetting selected index on child key changes, and this imagesLoaded on update. I'd recommend that since it's a single component.

Issuing a PR with that change is no problem, but I'm not in the habit of doing that without maintainer buy-in since they will likely be the ones supporting any changes.

yaodingyd commented 4 years ago

Can you do a PR? It makes sense to me

matthewlein commented 4 years ago

PR is open now.