I have a component in React/NextJS like this:
import Link from 'next/link';
<Link className={styles.slidercontentbottom} href="/projects" onClick={(event)=> console.log(event.target)}>
<button onClick={goToPreviousSlide}
className={styles.sliderbtnleft}>
<AiOutlineArrowLeft/>
</button>
<div className={styles.sliderfeature}>
<h1 className={styles.featuretitle}>Some text</h1>
<p className={styles.featuretext}></p>
</div>
<button onClick={goToNextSlide} className={styles.sliderbtnright}><AiOutlineArrowRight/>
</button>
</Link>
So it's a page with a slider background, where you can slide images. When I click anywhere on the screen it goes to /projects, which is my intention EXCEPT with the button left and right. When I click on them it slides the image and then immediately goes to /projects. Is there a way to prevent the navigation to /projects after clicking the button?
CodePudding user response:
You can use preventDefault and stopPropagation. You can change the default behavior button.
onClick={(event)=> event.preventDefault()}
And if you try this way, please improve your sample code for solution.
CodePudding user response:
Sure is!
If you look at your code, you'll notice the entire code block is wrapped in a <Link>
To do what you need to, just put the link deeper into your component tree to just wrap the background, and not the buttons like this:
<>
<button onClick={goToPreviousSlide} className={styles.sliderbtnleft}>
<AiOutlineArrowLeft />
</button>
<Link
className={styles.slidercontentbottom}
href='/projects'
onClick={(event) => console.log(event.target)}
>
<div className={styles.sliderfeature}>
<h1 className={styles.featuretitle}>Some text</h1>
<p className={styles.featuretext}></p>
</div>
</Link>
<button onClick={goToNextSlide} className={styles.sliderbtnright}>
<AiOutlineArrowRight />
</button>
</>
You may also notice we replaced the Link
component with <>
, which is a shorthand for an empty React Fragment. This is because a React component must only have one top-level element.