Skip to content

Commit

Permalink
fix: initializing swiper for multiple blocks (#476)
Browse files Browse the repository at this point in the history
Swiper wasn't initializing for additional blocks because `componentDidUpdate` (where we initialize Swiper) is not called for them. The reason that only the first block is calling `componentDidUpdate` is that the `latestPosts` prop is empty on mount and changes once the request is done, triggering the update. That is not the case for additional blocks because the `latestPosts` data is already there. Initializing `Swiper` on `componentDidMount` (if posts are available) fixes the issue.
  • Loading branch information
WunderBart authored May 15, 2020
1 parent a92c09e commit f480d54
Showing 1 changed file with 30 additions and 19 deletions.
49 changes: 30 additions & 19 deletions src/blocks/carousel/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,12 @@ class Edit extends Component {
this.paginationRef = createRef();
}

componentDidMount() {
this.initializeSwiper( 0 );
}

componentDidUpdate( prevProps ) {
const { attributes, latestPosts } = this.props;
const { autoplay, delay } = attributes;

if (
prevProps.latestPosts !== latestPosts ||
Expand All @@ -64,24 +67,32 @@ class Edit extends Component {
this.swiperInstance.destroy( true, true );
}

if ( latestPosts && latestPosts.length > 0 ) {
this.swiperInstance = createSwiper(
{
block: this.carouselRef.current, // Editor uses the same wrapper for block and swiper container
container: this.carouselRef.current,
next: this.btnNextRef.current,
prev: this.btnPrevRef.current,
play: this.btnPlayRef.current,
pause: this.btnPauseRef.current,
pagination: this.paginationRef.current,
},
{
autoplay,
delay: delay * 1000,
initialSlide,
}
);
}
this.initializeSwiper( initialSlide );
}
}

initializeSwiper( initialSlide ) {
const { latestPosts } = this.props;

if ( latestPosts && latestPosts.length ) {
const { autoplay, delay } = this.props.attributes;

this.swiperInstance = createSwiper(
{
block: this.carouselRef.current, // Editor uses the same wrapper for block and swiper container.
container: this.carouselRef.current,
next: this.btnNextRef.current,
prev: this.btnPrevRef.current,
play: this.btnPlayRef.current,
pause: this.btnPauseRef.current,
pagination: this.paginationRef.current,
},
{
autoplay,
delay: delay * 1000,
initialSlide,
}
);
}
}

Expand Down

0 comments on commit f480d54

Please sign in to comment.