Issue with the Material UI Dialog persisting even after clicking on the overlay

Recently, I crafted a reusable dialog/modal using React and Material UI. However, I encountered an unusual issue when attempting to close the modal by clicking on the overlay. Instead of the modal closing as expected and setting 'open' to false, it mysteriously reverts back to true.

The problem seems to be originating from the handleClickOpen function which triggers when clicking on the overlay, but I can't seem to pinpoint the exact cause.

Here is the Dialog component snippet:


const { onClose, open } = props;

const handleClose = () => {
onClose();
};

const preventDef = (e) => {
e.stopPropagation();
};

return (
<Dialog open={open} onClose={onClose} className={className} onClick={handleClose}>
<Container>
<Grid container className={`${className}__container`}>
<Grid item xs={12} sm={props.colsAmount} onClick={preventDef} className={`${className}__column`}>
{props.component}

{props.closeButton && (
<div className={`${className}__close`} onClick={handleClose}>
<Close />
</div>
)}
</Grid>
</Grid>
</Container>
</Dialog>
);

Now, let's take a look at the component where I load and trigger the dialog:


const [open, setOpen] = React.useState(false);

const handleClose = (e) => {
setOpen(false);
};

const handleClickOpen = () => {
setOpen(true);
};

return (
<div className={[classes.ShopCard]} onClick={handleClickOpen}>
<div className={`${classes.ShopCard}__image`}>
<div className={`${classes.ShopCard}__image__wrapper`}>
<img src={image} alt={alt} />

<div className={`${classes.ShopCard}__image__price`}>Vanaf €{price}</div>
</div>
</div>

<div className={`${classes.ShopCard}__content`}>
<Title title={title} size="h6" />
<Body>{description}</Body>
</div>

<div className={`${classes.ShopCard}__button`}>
<Button label="In winkelwagen" startIcon={<AddShoppingCart />} />
</div>

<CustomDialog
open={open}
onClose={handleClose}
colsAmount={6}
component={<ShopPopUp />}
closeButton="true"
/>
</div>

If anyone can shed some light on why the open state keeps getting set to true unexpectedly, please share your insights!

Answer №1

The reason behind this behavior is:

<div className={[classes.ShopCard]} onClick={handleClickOpen}>

It is positioned higher in the DOM hierarchy compared to the overlay, causing it to trigger consistently.

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

React - Update button to display loading status during data retrieval

I've experimented with different approaches, but haven't been successful in getting it to work. My goal is to have a button that is disabled until the fetch request returns a status of 200. Essentially, I want the user to be unable to proceed to ...

What causes the `this` keyword to point to the Window rather than the Component in the onClick() method of React

After working with React for a while, I always assumed that the this keyword would refer to the component itself. However, in my toggleStyle method below, I noticed that instead of referencing the React component object, this is actually returning the wi ...

How can I prevent the 'eslint(react-hooks/exhaustive-deps)' error from occurring on a custom React Hook that uses useCallback?

Here is a custom React Hook designed to work with the IntersectionObserver: import { useCallback, useRef, useState } from 'react'; type IntersectionObserverResult = [(node: Element | null) => void, IntersectionObserverEntry?]; function useIn ...

I am facing an issue with my react-app where it compiles successfully without any errors, but it is not rendering any elements

JavaScript file to run with npm start: import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import Routes from './routes'; ReactDOM.render( <R ...

What is the process for rendering a new component in React by utilizing the onTitleClick property of Material-UI AppBar?

Looking for a way to incorporate a new component by utilizing the onTiTleClick property. Below is the code snippet for my component: import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from ...

Strange error message: Attempting to set properties of null (changing 'innerHTML')

I have been working on a project where I am creating a website that retrieves data from a specified URL, displays it on the front end, and performs certain functionalities with that data (although this part is not yet implemented). However, I have encounte ...

What is the best approach to structure a React project in which a component's rendering changes with each instance?

I am facing a challenge with rendering a component that relies on multiple AJAX calls to complete. These AJAX responses return different data each time, and I want to implement a button that will trigger the re-rendering of this random component every time ...

When attempting to test actions with jest, an error is being thrown indicating that the module cannot be found, even though it

Currently, I am working on writing unit tests for Redux actions. At the moment, there are no other tests being executed. When I run `npm run test`, it locates the test file for actions and proceeds to run it. However, during the test execution, an error is ...

Disable form input fields while keeping all other elements enabled

Currently, I am facing a dilemma where I must deactivate specific input fields within a form. Given that there are numerous fields to consider, individually disabling each one seems impractical. Can anyone offer advice on how to disable a set of elements ...

Issue: Assertion violation: The use of <Link> element is restricted to within a <Router>. Any solutions or suggestions?

In my React and Next Js application, I am utilizing react-router-dom for routing purposes. The dependencies listed in the package.json file are as follows: This is how my current package.json file looks: { "name": "MUSIC", "versio ...

What methods do you use to gather user inputs and transmit them to a server?

I've been struggling to find information online about how to capture user input and submit the data through a POST request to a server, even though this may have already been answered. Currently, I am working with Material UI, React, and JavaScript t ...

What are some ways to customize a React Material-UI Required TextField?

The official documentation mentions the possibility of adding custom CSS to a TextField component. For example, in the provided snippet, the second TextField changes color to purple upon being clicked: <TextField className={classes.margin} I ...

Creating GraphQL from a Mongoose model: A step-by-step guide

I'm currently utilizing graphql and mongodb to add a specific object to the database. While using the same method to add an object, this particular one has a nested structure. package.json { "name": "workplaces", "versi ...

Building a React component that's a table containing rows that can be scrolled and elements that are clickable

Imagine having a set of events and their respective participants: const myData = { "event_1": ["1", "2","3"], "event_2": ["11", "5","8", "9"], "event_3&quo ...

Having trouble sending a file from React to Express using axios.post

Despite my best efforts, I can't seem to get this axios.post request working properly in React. I need to pass multiple values, including a PDF file, but it's not coming through correctly on the Express side. The strange thing is, when I console. ...

Using either Google Maps or a customized mapping solution in a React Native application

I am currently developing an application that allows users to input addresses and locate them on a map. I am wondering if implementing AI technology or utilizing specific libraries is necessary in order for this feature to function properly within a reac ...

Achieve a two-column layout in react-admin by leveraging the fullWidth property in SimpleForm or TabbedForm

My goal is to create an edit form with two columns. While I know that it can be done using a custom form, I am curious if there is a simpler way to achieve this using the existing SimpleForm or TabbedForm components. I have managed to display the data in ...

Tips for concealing XHR Requests within a react-based single page application

Is there a way to hide the endpoint visible in Chrome's devtools under the network tab when data is fetched in React? Can server-side rendering solve this issue? ...

Enzyme locates and chooses the initial occurrence of an element

I am attempting to simulate a click on the initial box out of three. My React script appears as follows: const Boxes = (props) => { return ( <div className="container"> <div onClick={props.showMessage} className="box">One& ...

Can the pathway of a fixed .txt document be reconfigured in Next.js?

I need some help with my Next.js application. I have a robots-staging.txt file located in the root of the public folder and I want to include it in the rewrites function within next.config. async rewrites() { const rewriteList = [ { sourc ...