yaodingyd / react-flickity-component

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

Can't select cell unless I directly pass the ID #115

Closed MartinConde closed 1 year ago

MartinConde commented 3 years ago

Basically I have a dropdown in which each option has an attribute corresponding to the ID of an image. My goal is to go to that image when an option is chosen. For that I am trying to use:

  const myCustomNext = () => {
    flkty.selectCell(somevar)
 };

somevar is initially set to #someid, when I click my button, it goes to the cell with that ID perfectly.

The issue starts once I update the value of somevar. As soon as I do and then click the button, I get the following Error: "Cannot read property 'selectCell' of null"

I logged both the initital somevar and the updated one. Other than the ID itself, they are absolutely identical so I have no clue where I am going wrong. I tried switchen the static and reloadOnUpdate settings but that didn't help.

Here a more complete example that might show better what I am trying to do:

const FlickTest = () => {

    const [varimg, setVarimg] = useState("#cG9zdDoxNA");
    let flkty = null;

    function setVariant(e) {
        let index = e.target.selectedIndex;
        let optionElement = e.target.childNodes[index]
        let option = optionElement.getAttribute('data-imgid');
        setVarimg(`#${option}`);

    }

    const myCustomNext = () => {
        flkty.selectCell(varimg)
    };

    return (
        <>
            <button onClick={myCustomNext}>My custom next button</button>

            <select onChange={setVariant}>
                {variants.map((variant) =>
                    <option data-imgid={variant.gallerie[0].id} value={variant.farbe} key={variant.farbe}>{variant.farbe}</option>
                )}
            </select>

            <Flickity
                flickityRef={c => (flkty = c)}
                className={'carousel'}
                elementType={'div'}
                options={flickityOptions}
                disableImagesLoaded={true}
                reloadOnUpdate={true}
                static={true}
            >
                {variants.map((galitem) =>
                    galitem.gallerie.map((galimg) =>
                        <div key={galimg.id} id={galimg.id.replace(/[^\w\s]/gi, '')}>
                            <span>{galimg.id}</span>
                            <Image fluid={galimg.localFile.childImageSharp.fluid} />
                        </div>
                    )
                )}
            </Flickity>
        </>
    )
}

Any ideas or pointers would be much appreciated :)

yaodingyd commented 3 years ago

You should use a ref or a variable outside of your functional component scope to assign flickityRef, because the current flkty gets re-initialized everytime it renders