Clicking on components that are stacked on top of each

I am facing an issue with two React arrow function components stacked on top of each other using absolute positioning. Both components have onClick attributes, but I want only the one on top to be clickable. Is there a workaround for this?

Here is a simplified version of the code:

const Card = ({...}) => {

    const styles = {
        optionsButton: {
            minWidth:0,
            minHeight: 0,
            padding: "2px",
            position: "absolute",
            color: "#808080",
            zIndex: 1,
            right: 5,
            top: 5,
            '&:hover':{
                backgroundColor: 'rgb(0, 0, 0, 0.1)'
            }
        },
    }

    const [hovering, setHovering] = useState(false)
    const [isCardExpanded, setIsCardExpanded] = useState(false)

    const expandCard = () => {
        setIsCardExpanded(true)
    }
    const closeCard = () => {
        setIsCardExpanded(false)
    }


    const mainPaperStyle = () => {
        let style = {
            padding: "10px",
            cursor: "pointer",
            position: "absolute",
            "&:hover": {
                filter: "brightness(97%)"
            }
        }

        //Extra code here modifying color of the style, no positioning modifications

        return style
    }

    const buttonAction = () => {
        console.log("Do action!")
    }

    return(
        <>
            <Paper sx={mainPaperStyle()} onClick={expandCard} onMouseEnter={() => setHovering(true)} onMouseLeave={() => setHovering(false)}>
                Lorem Ipsum

                {hovering &&
                    <Button variant="filled"
                            id="card-button"
                            sx={styles.optionsButton}
                            onClick={() => buttonAction()}>
                        <MoreVertIcon/>
                    </Button>
                }
            </Paper>
        </>
    )
}

Below are screenshots illustrating why I need two components stacked:

When hovering over the Paper component, a Button should appear. However, the issue arises when clicking the button as both expandCard and buttonAction functions trigger simultaneously. (I am using Material UI by the way)

Answer №1

To prevent event propagation, you can utilize the $event.stopPropagation(); method.

const firstFn = () => { // logic for the first function };
const secondFn = (event: MouseEventHandler<HTMLButtonElement>) => { 
    $event.stopPropagation();
    // logic for the second function
}

In your specific scenario, it is necessary to update the buttonAction function as follows:

const buttonAction = (event) => {
    $event.stopPropagation();
    console.log("Perform action!")
}

Additionally, modify the return statement with the following changes:

return(
        <>
            <Paper sx={mainPaperStyle()} onClick={expandCard} onMouseEnter={() => setHovering(true)} onMouseLeave={() => setHovering(false)}>
                Lorem Ipsum

                {hovering &&
                    <Button variant="filled"
                            id="card-button"
                            sx={styles.optionsButton}
                            onClick={() => buttonAction($event)}>
                        <MoreVertIcon/>
                    </Button>
                }
            </Paper>
        </>
    )

For more information on this topic, refer to this resource

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

Developing a React application build

As a newcomer to React, I have successfully deployed a small working prototype of a React application on AWS ECS as a docker container. This app was created using "create-react-app" with the following Dockerfile: FROM node:alpine as build WORKDIR /app COPY ...

Using React hooks and Typescript: I was expecting to see an assignment or function call, but instead, an expression was

After working as a React developer for quite some time, my workplace recently introduced Typescript, which I am still getting familiar with. I implemented a custom hook for managing cookies, but the function it returns is generating an error. Here's ...

How come Express GET requests always provide HTML as the response content type?

I'm facing an issue where my API GET routes always return HTML instead of JSON data. Here's an example of the code causing the problem: router.get("/allposts", auth, async (req, res) => { try { const Posts = await Post.fi ...

Adjust the background color of the header as you scroll

Seeking assistance in adjusting the background color of my header upon scrolling. This is my current implementation: header.component.ts export class HeaderComponent { ngOnInit(): void { const header = document.querySelector('.header'); ...

I'm having trouble getting my HTML <button> element to function correctly

I'm currently working on a project where I need to animate a green bar moving upward over a blue bar when a button is clicked. However, no matter what I try, the button doesn't seem to be working. I've experimented with using both the button ...

Experiencing a dilemma with Watchman in React Native

To refresh the application, press "r" To access the developer menu, press "d" Received an error from jest-haste-map: Watchman crawl failed. Trying once more with node crawler. This typically occurs when watchman is not running. You can create an empty ` ...

How to Use CSS to Copy a Style Path and Conceal an Element within an iFrame

My goal is to adjust a division by including a width element in its CSS properties. I have attempted to use Chrome and Firebug to copy the CSS path, but it seems that the result is incorrect. After inserting it into my style.css file, the division remains ...

Using gradient colors for the background on the ::selection pseudo-element

Can you apply a gradient color to CSS ::selection? I tried using the following code: ::selection { background-image: -webkit-linear-gradient(left, #ee4037 0%, #eb297b 100%); } However, it did not have the desired effect. ...

What could be causing the discrepancy in sizes of the columns in my multi-column layout?

https://jsfiddle.net/drqjmssy/ Seeking assistance from the linked jsfiddle, I aim to align "div class='main_content'" vertically with "div class='sidebar'". What would be the best approach to achieve this alignment? In case the fiddle ...

Is there a way to create an image gallery layout similar to Pinterest using CSS?

I am currently developing a dynamic PHP gallery that will feature thumbnails with the same width but varying heights. These thumbnails will be arranged from left to right, so I would prefer not to use a traditional five-column layout. I suspect that achiev ...

Is there a way to properly access and interpret a .log extension file within a React component?

import React from "react"; import "./App.css"; function FileReaderComponent() { const readLogFile = () => { if (window.File && window.FileReader && window.FileList && window.Blob) { const preview = document.getElementByI ...

Is it recommended to store all data (such as images, profile information, user details, etc.) in the redux-persist store while using react-redux

As I embark on my journey with Redux, I've been considering a more streamlined approach to storage by utilizing a tool called "Redux-persist." This tool allows the Redux store to persist even when the window is closed, consolidating all data in one pl ...

Tips for creating a dynamic variable for an object key in jQuery to streamline your code

Utilizing the TweenMax library, I am adding styles to a div while scrolling. However, I am facing a challenge where I need different styles based on varying page resolutions. To address this issue, I implemented an if condition. Is there a way I can use a ...

Utilizing React Router with the power of useCallback

My route configuration is set up as follows: const defineRoutes = (): React.ReactElement => ( <Switch> <Redirect exact from="/" to="/estimates" /> <Route exact path="/estimates" component={CostingPa ...

What is the best way to transfer information between two React.js files?

I am currently finding it inefficient to pass data from App.js to another .js file within React by constantly reading and writing from local storage. I would prefer to only retrieve data from local storage once when the App.js component mounts. App.js: ...

Prior to stacking the divs, separate the line within the div

In the process of creating a responsive navbar with Bootstrap, I encountered an issue. When resizing the window to a smaller size, the collapse icon shifts from the top right position below my "logo". Here is how the site appears on a regular screen: http ...

Utilize Material UI Slider to show only the minimum and maximum markLabels on display

I recently started using Material Ui and I'm having trouble figuring out how to show only the lowest and highest markLabel in a Material UI slider component. range slider For this specific example, I want to display "1888" and "2019" only. Apprecia ...

The React Router test commences outside of the home page

While testing my App component, I encountered an issue during the second test. In the first test, the process begins from the home page where I click on a drink-preview to access a recipe. However, in the subsequent test, which is expected to follow the sa ...

Attempting to alter the background image through the action of clicking on an image using jQuery, HTML, and CSS

I have created custom weather icons like a sun, cloud, and rainy cloud using Photoshop. My goal is to allow users to click on these icons and change the background image of the website's body. However, despite my efforts, clicking on the images does n ...

Next.js Adsense Ad Units

I am seeking assistance with incorporating Adsense ad units into nextjs. I have already implemented the auto-generated ads successfully, but I would like to customize them further. This is what I have done so far, but I am unsure if it is the optimal appro ...