How to implement a button using react-router's Link component?

Imagine having an element structured like this:

<Link to={`/games/${game.id}`}>
  <GameInfo/>
  <CustomButton/>
</Link>

https://i.sstatic.net/0qqOV.png

Can the button inside the link act independently from the link itself without relying on the z-index css property? The goal is to maintain the current behavior where hovering over the button triggers both the hover effect for the button and the link below.

Currently, when clicking on the Add to Library button, the game gets added to the library but it also triggers the Link below, unintentionally opening the game profile page.

The only solution I have thought of so far is something like this:

  <div> // <= move link hover effects here
    <Link to={`/games/${game.id}`}>
      <GameInfo/>
    </Link>

    <CustomButton/>
  </div>

However, this workaround is not ideal because I still want the area around the button to be part of the Link (ensuring hover and functionality in the specified areas).

https://i.sstatic.net/swEVc.jpg

Is there any alternative to using z-index in this scenario?

Answer №1

To accomplish this effect within a button click event, you can utilize preventDefault and stopPropagation as shown below:

<Link to="/game">
      <div>
      
        <button
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
           //function to do your stuff
          }}
        >
         Click Me
        </button>
      </div>
    </Link>

For a demonstration, you can view the demo by visiting the following link:

https://codesandbox.io/s/adoring-sun-dwnde?fontsize=14&hidenavigation=1&theme=dark

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging Ramda's pipe function in developing React applications

In my current setup with ramda and react, I have a container component "a" and higher order components x, y, and z. export default R.pipe( x, y, z )(a) Each component is defined as follows: const x, y, or z = C => props => <C {...prop ...

Tips for creating a mobile-friendly Bootstrap carousel that is both scalable and zoomable while maintaining the default slide functionality

I have a website using Bootstrap 4.x carousel. The layout is user-scalable with the following viewport meta tag: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2, shrink-to-fit=no">. Currently, users can pinch to z ...

When the appdir is utilized, the subsequent export process encounters a failure with the error message "PageNotFoundError: Module for page /(...) not

I have implemented NextJS with the experimental appDir flag and organized my pages in the following manner: https://i.stack.imgur.com/M7r0k.png My layout.tsx file at the root and onboard look like this: export default function DefaultLayout({ children }) ...

The dangers posed by vulnerabilities in the React library

Hi there, I just finished setting up react-redux and noticed some vulnerabilities showing up in my console - both low and high. Can anyone explain what this means and if I should consider uninstalling it? ...

What's the best way to align two elements side by side regardless of window size changes?

I am looking to keep these two elements together in one row at all times, regardless of if the window is resized horizontally. Currently, they break into two rows as shown in this screenshot: http://gyazo.com/1820dc436dba2e827b330039109dc0ee I attempted ...

Tips for applying a CSS class with a smooth fade-out effect

In my Angular project, I am working on creating a custom notification component. Here is the template code I have so far: <aside *ngFor="let message of messages "> <div class="notification" style="position:fixed"> {{message.conten ...

Preloading Images in Next.js: How to Load Images on Website Launch Before Reaching the Displayed Page

I am currently working on a website with a gallery using nextjs. I am trying to preload all the assets from the gallery as soon as the page loads, but I can't seem to figure out how to do it. I've attempted hiding a link to the gallery in various ...

What's the reason behind Next.js including a ?ts query parameter in static JS files which is causing them to not be loaded from cache?

Each time a page is loaded, Next.js retrieves the same JS files using a query parameter like ?ts=1234. For example: /_next/static/chunks/pages/_app.js?ts=1671033077175 /_next/static/chunks/main.js?ts=1671033077175 This practice seems to be in place to pr ...

Creating a dynamic step animation with jQuery: A step-by-step guide

Struggling to find resources on how to animate a color wheel using jQuery? Want to create a spiraling effect by gradually revealing colors at 45-degree intervals, like a loading GIF spiral? I need it to cycle through the defined colors in order and then cl ...

Controlling opacity with jQuery animate() function using a click event

I have a specific requirement for an animation. When the button is clicked, I need the element to transition from 0 opacity to full 1 opacity within 300 milliseconds. The issue I am facing is that when the button is clicked, the animation does not work a ...

Only conceal the table column if space is limited

A scenario involves an HTML table with two columns that need to be displayed fully, with the second column aligned to the right. Currently, this has been achieved by setting the width of the first column to 100%. However, a challenge arises where the words ...

Having trouble with the callback function for the "One Tap" feature in React not being triggered? Look it up

<script src="https://accounts.google.com/gsi/client"></script> ... declare var google: any; ... useEffect(() => { const handleCredentialResponse = (response: any) => { console.log(response); }; const client_id = proce ...

Styling a PrimeFaces panelGrid within a data table using CSS

I am struggling to add a background color to a panelgrid within a datatable when a hover event occurs. Despite writing the necessary code and CSS, nothing seems to work. Any suggestions on how to address this issue? <p:dataTable id="movementsTable" var ...

Having trouble getting the onClick function to work in your Next.js/React component?

Recently, I delved into using next-auth for the first time and encountered an issue where my login and logout buttons' onClick functions stopped working when I resumed work on my project the next day. Strangely, nothing is being logged to the console. ...

The useEffect function is failing to execute, leading to an issue with an undefined variable

Attempting to retrieve a specific string with the help of useRouter, then utilizing that same string to access a particular document from Firebase is my current goal. This sequence of actions is supposed to take place within the confines of the useEffect f ...

react Concealing the Card upon clicking a different location

Utilizing a combination of React and TypeScript, this component allows for the card to be toggled between shown and hidden states upon clicking on the specified div tag. However, there is a need to ensure that the card is hidden even if another area outs ...

Subcomponents failing to refresh overarching state variables

I'm currently working on a form that involves controlled components, Material-UI, and React hooks. The form data is stored in a global state using a useState setter function. Furthermore, certain fields need to be toggled on and off based on the user& ...

Is it possible to ensure that an asynchronous function runs before the main functional component in React js?

My challenge involves extracting data from an API by manipulating a URL. Specifically, I must retrieve a specific piece of information upon page load and then incorporate it into my URL before fetching the data. var genre_id; var genre; const MOVIE_URL = ` ...

How come this particular design is being passed down from a predecessor (and not a direct parent) div?

Web development can be frustrating at times. Hopefully, someone out there can shed some light on this issue and offer a solution. You can view the HTML/CSS code below or check out this example on JSFiddle The problem arises when I have a header div and a ...

Tips for specifically targeting the accordion panel header when it is clicked

I am currently facing an issue with my accordion that contains lengthy text in the panel body. When I open any accordion, the page scrolls to the top and part of the text gets cut off. Is there a way to fix this problem or do I need to focus on the panel-h ...