Concealing a Div on Click Outside of Child Div in ReactJS

I have a parent div with a child div in the center. I am trying to figure out how to close the parent div only when clicking outside of the child div. My current code is structured like this, using triggerParentUpdate to control whether the div should be displayed or not.

<div onClick={this.props.triggerParentUpdate} className="signupModalContainer">
    <div className="embed-responsive embed-responsive-16by9">
        <form action="action_page.php">
            <div className="container">
                <button onClick={this.props.triggerParentUpdate} type="button" className="closebtn">X</button>
            </div>
        </form>
    </div>
</div>

The onclick function in the parent div (className="signupModalContainer") currently closes all the divs when clicked, including the child divs. If I remove this function, only the close button can close the divs.

Any suggestions on how to achieve the desired functionality are appreciated. Thank you!

Answer №1

Implement a handler for the child div's onClick event listener, specifically designed to prevent the event from bubbling up to the parent element.

For more detailed information, you can visit Event.stopPropagation.

class SomeComponent extends Component {
  handleCloseButton = e => {
    // Use this method to stop the event from propagating upwards.
    // This way, the parent div's "onClick" event will not be triggered.
    e.stopPropagation();
    this.props.triggerParentUpdate(e);
  }

  render () {
    // ...
    return (
      <div onClick={this.props.triggerParentUpdate} className="signupModalContainer">
          <div className="embed-responsive embed-responsive-16by9">
              <form action="action_page.php">
                  <div className="container">
                  <button onClick={this.handleCloseButton} type="button" className="closebtn">X</button>                             
                  </div>
              </form> 
          </div>
      </div>
    );
  }
)

Answer №2

Detecting clicks in the parent element is a simple task

   const checkParentClick = event => {
    event.preventDefault();

    if (event.target === event.currentTarget) {
      console.log('parent clicked');
      // 👇 add your custom logic here
    }
  };

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

What is the reason for my backend being called twice for every request with the useSWRInfinite function

I have implemented a load more button in a new Next.js application, utilizing the useSWRInfinite hook. Each time the button is clicked, it triggers two calls to the backend. The first call is made with index 0 and the second one with the incremented index. ...

Ways to expand a TypeScript interface and make it complete

I'm striving to achieve the following: interface Partials { readonly start?: number; readonly end?: number; } interface NotPartials extends Partials /* integrate Unpartialing in some way */ { readonly somewhere: number; } In this case, NotPar ...

Live Edit API

Currently, I am developing an application that requires near real-time collaborative editing capabilities for documents, similar to the functionality found in Google Documents. Since I am a beginner in this area, I would greatly appreciate any information ...

Easily switch between visible and hidden content by clicking on an image that functions as a swap or toggle

Hey there, I'm new to this and could really use your assistance, I'm looking for a simple show/hide toggle feature when clicking on an image, where it switches between a 'side arrow' and a 'down arrow' (similar to a dropdown) ...

eliminate whitespace characters within a string

Here is a question that suggests an easy way to remove space characters in a string using R. However, I encountered an issue when trying to remove a space between two numbers (e.g. 11 846.4) while working with the following table: require(XML) require(RCur ...

What is the reason that my "width: auto" property is not properly adjusting to the content's width?

My css code, width: auto is causing issues with the content width I am a beginner in HTML, CSS, and JavaScript, seeking help with my website. I have multiple divs within a section element, but the section's width is not adjusting to fit the divs prop ...

Having trouble retrieving user login information in Postman

I have encountered an issue while creating a REST API using Node js and expressJs. When attempting to create a user, I successfully implemented the following code: /** * save user data from the user model */ router.post("/users", async (req, res) => ...

Building connections in parse.com using various classes (JavaScript SDK)

Currently using parse.com in conjunction with the JavaScript SDK. Despite my extensive research, I have been unable to find any examples that directly address the issue I am facing. Here is the specific goal I am striving to accomplish: I aim to establi ...

Tips for restricting text within a div container

Currently, on my to-do list website, I am facing an issue with displaying long event titles in a div on the home screen. The text overflows, and even though I have set the x-overflow to hidden, it's not providing the desired result. I have tried using ...

JavaScript inserted into debug console by developer

Is there a method to troubleshoot code that has been added through the firefox developer console terminal? For example, I added document.onkeydown = function(event) { // code logic for checking keys pressed } If only I could determine which .js file t ...

I'm only seeing output on two of my input boxes - what's going on?

Currently in the process of learning JQUERY/HTML, I decided to create a shopping cart. My goal is to display the subtotal, tax, shipping costs, and total cost in input boxes. While I successfully displayed the sub total and shipping cost, I encountered an ...

Tips for effectively sharing content on social media from your Vuejs application

I have been using the vue-social-sharing library to enable social media sharing on my website, and overall it's been working well. However, I am facing a problem where when I click the Facebook share button, it doesn't share the title, descriptio ...

An issue occurred while calling the Selenium web driver: the driver.get() function couldn't access the attribute "href" of the linked_url, resulting in a stale element reference

Currently, I am utilizing Python with Selenium to work on extracting links from Google search results. After successfully accomplishing this task, I am now attempting to navigate through these links one by one using a for loop and the driver.get() method: ...

Using a Material-UI component to activate a React Router Link

Currently, I am facing an issue while using material-ui components in react with react-router. The problem arises when I try to display list-items that double up as link elements but also have a submenu inside which should not activate the parent link. Unf ...

Issue with Parcel 2 - Error encountered: Module 'axios' not found

I have enrolled in a Udemy course called 'Node.js, Express, MongoDB & More'. The instructor uses parcel v1 in the course, but now that parcel has released v2, I am facing issues installing v1. I am attempting to access the file from the dist dire ...

Resolve issue with header in scrollable material-ui popover

Material-UI allows for a fixed header and footer in a Dialog with long, scrolling content. I am looking to achieve the same effect but within a popover. For example: <Popover> <Header>Fixed header</Header> <Content>long long ...

What is preventing me from successfully retrieving data at times when using curl_setopt and jQuery Ajax?

In my quest to fetch data from another server, I am using the curl_setopt PHP function along with Ajax. The function I have created seems to be working fine, but sometimes when I refresh the page and the internet connection is slow, I don't receive an ...

How to Incorporate LessCSS into the Blueprint Framework?

Can LessCSS be integrated with Blueprint framework? What are the prerequisites for starting? ...

Sending the most recent result to each dynamically created div

In my WordPress project, I have an event panel that displays upcoming event details and shows the remaining time until the next event. The countdown dynamically gets values from the database and calculates the time left based on the user's input in th ...

Starting a tab just once

I have successfully created 4 static HTML pages that include: Home About Services Contact Each page contains a link that leads to another static page named myVideo.html, which plays a video about me in a new tab. The link is available on every page so ...