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

When creating a FlipCard, you may encounter the error message "The object may be null" while using the document.querySelector() method

Having trouble creating a flipcard on Next.js with tsx. The querySelector('.cardflipper') doesn't seem to locate the object and I keep getting this error: "Possibly the object is null". Does anyone know a solution to help my method recognize ...

Tips for achieving a Google Map that smoothly slides behind a sticky header as you scroll

I recently added a sticky header using CSS to my long HTML page. At the bottom of the page, there is a <div> element with a Google Map embedded in it. As I scroll down the page, the content scrolls behind the sticky header as expected, but the Googl ...

Guide for integrating images in React Native

I am struggling to display images in a carousel properly. I attempted to require them using JSON like this {"Image": require("$PATH")} or in a js file within the ParallaxImage tag, but nothing seems to work... Item Creator _renderItem ...

I am having trouble implementing internal/inline styles on dynamic elements within NextJs

I am struggling with formatting a code snippet similar to this one: <p className="xyz" dangerouslySetInnerHTML={{__html: dynamicContent}}></p> In the dynamicContent variable, there is a string and an anchor tag. I want to apply some ...

The documentation for Storybook MUI v5 fails to generate

Using material UI V5 with story book has been a breeze, except for one issue - the docs are not generating automatically. Clicking on the "docs" tab only leads to a blank white screen. To troubleshoot, I checked out a repository that utilizes Material Ui ...

The React application deployed on GitHub Pages is displaying a blank white screen

I developed a simple meme generator app in React.js as an exercise to learn web development, but I am facing issues while trying to host it on Github pages. I followed all the necessary steps such as installing gh-pages with node, updating packages.json wi ...

Created using Node.js version 10, this revolutionary React application is taking the

I inherited a main react application that hosts several other react applications. As new applications continue to be developed, I became concerned about the use of nodejs10 for each new project. Is it possible that issues may arise in the future due to t ...

Issue with updating state following data retrieval in React hooks

Recently, I've been experimenting with an API and working on a React application for data display. However, I encountered an issue while setting the state using the setState method of React Hooks after sending my information through a form request via ...

Ways to invoke a method in the parent component using a component/reactnode passed as props in a React application

I need to customize the Button component inside my Toast component. When I click on this custom button, I want it to call a method within the Toast component. Here is an example of how you can use the Toast component: const actionButton = ( <Mybutton ...

The cakePHP time dropdown feature lacks customization options

When viewing my form in CakePHP, I noticed that the time select dropdown appears differently in Chrome compared to Firefox. In Firefox, there are 3 arrow buttons attached to each dropdown, whereas in Chrome it looks different. I want to hide the arrow but ...

Center Items in Flexbox, Implementing React Material with React

In my React App, I am utilizing flexbox and React Material to align the searchbar and clear button on the same line with space between them. Here is the link for reference: CLICK HERE <div className={classes.searchBarSection}> <Paper com ...

When the menu active item is clicked, the header will automatically scroll to the top

I've implemented a sticky header using CSS and JavaScript along with a mega menu. However, I've encountered an issue where when scrolling to the bottom and clicking on the "more" link in the dropdown, the page scrolls back to the top. This is the ...

Image expansion

I have a container element div that holds various content of unknown length. How can I add a background image that extends the entire length of the container since background-images do not stretch? I attempted to use a separate div with an img tag inside. ...

When using TypeScript and React with Babel, an error may occur: "ReferenceError: The variable 'regeneratorRuntime'

I've been delving into learning typescript, react, and babel, and here is the code I've come up with: export default function App(): JSX.Element { console.log('+++++ came inside App +++++++ '); const {state, dispatch} = useCont ...

Exploring cross-browser compatibility with the use of CSS3 and JavaScript

Starting a new project to create a fresh website. It seems like many people are leaning towards CSS3 and AJAX, neglecting browsers without JavaScript support. They resort to workarounds like enabling CSS3 through JavaScript in older browsers. Is this the ...

React's Tic Tac Toe game is experiencing issues with its reset button functionality

class App extends React.Component { constructor() { super(); this.state = { currentPlayer: false, //false is X, true is O message: null, gameOver: false, grids : { '0': null, '1': null, ...

Tips for adjusting an svg component to suit various screen sizes

I inserted the following SVG component into my HTML file. It fits perfectly on my tablet, but it's too large for my smartphone. How can we automatically adjust the size of the SVG to fit different screens? <svg viewBox="310 -25 380 450" w ...

Element with absolute position does not expand along with scrollable content (over 100%)

In my popup window, the fade element is supposed to stretch to the full width of the screen. However, when the content exceeds 100% of the browser window height, the element does not extend to the full page height. If I set html, body { height: 100%; over ...

Tips on tallying the frequency of items in a state array

I'm currently working on an application in which clicking a button adds the item's value to the state. The button is clickable multiple times, allowing the same item to be added multiple times in the state array. My current code snippet: export ...

How to Stop Element Flickering While Hovering in Selenium IE Webdriver

My code is functioning perfectly in Firefox, but when I try it on Internet Explorer, there is flickering. Here is my code: WebElement mouseOver= driver.findElement(By.linkText("abc")); //I'm locating the element by link text. Selenium finds the ...