Search code examples
reactjsreact-slick

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

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

  • It's 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 won't need options in state any more.

    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 they've 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>
    }