简体   繁体   中英

How to Call Function Before Link Element's onClick fires | Next.js

so I've run into a problem while making a slider/carousel. I have photos in each slider that should be able to be dragged back and forth, then when clicked, they take you to a product page. To do this I am using next.js with react-flickity-component . Note: this issue isn't specific to flickity.

So what going on is each element(as seen below) in the slider is wrapped in the nextjs link component. But after dragging the element the click event fires and erroneously takes the user to a product page. the link should only work if the clicks, without dragging. if the flickity drag event fires, I want to disable the onClick handler some how. I just don't know the Link component enough to know how to disable it.

I can query flickity to see when the drag has started, so I am looking for a way to conditionally disable onclick, or alter, the onClick event of the Link component.

        <Link href={href}>
            <div className={`carousel-cell ${cardStyles.card} ${className || ''}`}>
                <div className={cardStyles.tabVisualEffect} tabindex="0">
                    <Image src={imgUrl} className={"carousel-image"} layout="fill" />
                    <div className={cardStyles.overlayContainer}>
                        <div className={cardStyles.arrowContainer}>

                        </div>
                        <div className={cardStyles.titleContainer}>
                            <h3 className={cardStyles.cardTitle}>{title}</h3>
                            <h4 className={cardStyles.cardSubTitle}>{subtitle}</h4>
                        </div>
                    </div>
                </div>
            </div>
        </Link>

my question is how can i run a function before the Link elements onClick handeler runs?

You can define a custom component different from Link and implement the onClick props on it

<CustomButton onClick={() => {
  foo();
  router.push('/bar')
}}>
 . . .
</CustomButton>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM