kimcoder / react-simple-image-slider

simple image slider component for react
https://kimcoder.github.io/demo/react-simple-image-slider/
MIT License
163 stars 49 forks source link

Slider is re-rendering but not rendering new images unless nav buttons are clicked #77

Open AyoCodess opened 2 years ago

AyoCodess commented 2 years ago

I have modal which displays the image slider, i have a button that is called 'next post' which should render a new image slider and other info in the modal.

what happens is the slider gets re-rendered, the bullet points reflect the right number of new images in the new post, but the new images do not render unless i click the slider nav buttons. Can anyone help?

  const nextPost = () => {
    setPostImageArray(posts[postIndex + 1].images);
    setPostCaption(posts[postIndex + 1].caption);
    setPostIndex(postIndex + 1);
  };
Screenshot 2022-04-11 at 16 25 12
KristofferTolboll2 commented 2 years ago

@AyoCodess

I found a way to solve the issue. You need to pass a key property, that changes anytime the images change as well. Here is an example I made. I am using useMemo to map my images here, but you get the idea


export const SwipeCard = ({ user }: { user: FullUser }) => {
  const { photos, id } = user;
  const userImages = React.useMemo(() => {

    let images = [];
    images = photos
      ? photos?.map((photo) => ({
          url: photo.src,
          isBanned: photo.bannedAt !== null,
        }))
      : [{ url: "", isBanned: null }];
    return images;
  }, [photos]);

  return (
    <>
      {userImages?.length > 0 ? (
        <SimpleImageSlider
          width={800}
          key={id}
          height={750}
          images={userImages}
          showBullets={true}
          showNavs={true}
        />
...