Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

it's not working rerendering when array state change in react [react-slick]

enter image description here

This is my React code.
I use react-slick library.

I expect

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1. when clickedIndex changes
2. it calls useEffect
3. option state change
4. rerender this EnlargePhto component
5. StyledSlider is affected by changed option.
6. combineMood_1 array’s initialSlide = clickedIndex
7. ex) clickedIndex = 8 –> StyledSlider start at 8 image.

BUT,, it continuely starts at array’s first image.
how can i solve it?

>Solution :

Its probably because initialSlide only defines the default starting slide, and cant be used to control it thereafter.

What you need is a ref to the slider then call slickGoTo. You wont need options in state anymore.

The api of react-slick is a bit bad by the way — usually calling methods on a ref is an escape hatch and it’d just be a prop but…this is what theyve gone with.

const options = {
   // your existing options here.
   // They can now be defined outside the component as they never need to change anymore

}

function EnglargePhoto({combineMood_1, clickedIndex}) {
    const sliderRef = useRef(null)
    
    useEffect(() => {
        if (sliderRef.current === null) return // because on initial render it will not be set yet, since the DOM isnt rendered
        sliderRef.current.slickGoTo(clickedIndex)
    }, [clickedIndex])

    // return
    <StyledSlider {...options} ref={sliderRef}>
       // existing contents
    </StyledSlider>
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading