Issue with modal pop-up functionality (require background page to be dimmed)

On a page, there's a button overlayed that is supposed to dim the background and display a modal popup when pressed.

However, in my code, the modal popup appears but the background remains unaffected. The modal opens and closes correctly, though.

Button code:

class MessageBrokerButton extends Component {
    constructor(props) {
        super(props)
        this.state = {
            isShowing: false
        }
    }

    openModalHandler = (e) => {
        this.setState({
            isShowing: true
        });
        e.preventDefault();
    }

    closeModalHandler = () => {
        this.setState({
            isShowing: false
        });
    }

    render() {
        return (
            <div>
                <button className='message-broker' onClick={this.openModalHandler}>
                    Message Broker
                </button>
                <div className='message-icon'></div>

                { this.state.isShowing ?         
                    <Popup 
                        show={this.state.isShowing} 
                        close={this.closeModalHandler}>
                            Test
                    </Popup> 
                    : null 
                }
            </div>
        )
    }
}

Modal code:

const Popup = (props) => {
    return (
        <div>
            <button onClick={props.close}>CLOSE</button>
            <p> {props.children}</p>
        </div>
    )
}

Page code snippet where the button is placed:

class Page extends Component {
    constructor(props) {
        super(props);
        this.state = {

        };
    };

    render() {
        let page100 = 
        <div>
            <MessageBrokerButton></MessageBrokerButton>
        </div>

        if (this.props.currentPage !== this.state.page) {
            page100 = null;
        }

        return (
        <form onSubmit={this.handleFormSubmit}>

            {page100}

        </form>
        );
    }
}

I acknowledge that I may not be following correct styling rules and handling the Page class properly once the MessageBrokerButton is clicked. I need guidance on which parts to modify and what changes are necessary.

Answer №1

There are several approaches to achieve this functionality. One method is to create a Shadow sub-component nested within the main Page component. This Shadow component can be given a state property that dictates whether it should display the shadow overlay or not.

The implementation of this setup is relatively straightforward. The main challenge often lies in devising an effective state management system that allows for seamless control over the Shadow component without the need to pass the "enable shadow" function throughout the codebase. Consider exploring Redux as a potential solution for state management.

To ensure the proper display order, utilize the z-index CSS property to position the shadow element between the Page content and any modal popups. For instance, assign a lower z-index value (e.g., 1) to the shadow element and a higher value (e.g., 2) to the modal container. Additionally, both the shadow and modal container should have their positioning set to absolute to ensure they overlay the page correctly.

Below is a simplified example:

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hasShadow: false,
      modal: null,
    };
  }
  
  handleHasShadow = hasShadow => {
    this.setState({ hasShadow });
  }
  
  handleSetModal = modal => {
    this.setState({ modal });
  }
  
  render() {
    return (
      <div>
        <form ...>
          {this.props.currentPage === this.state.page
            ? <MessageBrokerButton handleHasShadow={this.handleHasShadow} />
            : null
          }
        </form>
        <Shadow isEnabled={this.state.hasShadow} />
        <ModalContainer>{modal}</ModalContainer>
      </div>
    );
  }
}

Shadow.jsx

const Shadow = ({ isEnabled }) => {
  return isEnabled ? (
    <div
      style={{
        position: 'absolute',
        top: 0,
        right: 0,
        bottom: 0,
        left: 0,
        background: '#000000',
        opacity: 0.5,
        zIndex: 1,
      }}
    />
  ) : null;
}

You can now toggle the shadow overlay with the help of the this.props.handleHasShadow(true/false) function. The shadow will automatically expand to cover the entire parent (Page) component.

Another consideration is implementing a focus trap within your modal to prevent users from tabbing out of its confines. This feature ensures that interaction stays within the modal dialog only.

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

Is it not possible to import in SCSS if the variable is equal to the value?

In my project, I am utilizing scss. There is a variable that determines which scss file needs to be imported based on its value. I attempted the following approach: $test: 1; @if $test == 1 { @import "./theme1.scss"; } However, an error message is dis ...

'Mastering the implementation of promises in React context using TypeScript'

I've been diving into the world of incorporating TypeScript in React and I'm facing a challenge with implementing async functions on context. The error that's popping up reads as follows: Argument of type '{ userData: null; favoriteCoc ...

What is a callback function tied to a specific URL?

I need to implement a functionality in my web application where users can click on a link within a datatable, which will then load a new table on a separate page. This new table should only display rows that have the same id as the row that was clicked on ...

Sending data to a React Dialog component using the OnClick event

I am a beginner learning React.js and currently experimenting with passing parameters to a dialog box using onclick events. <IconButton className={classes.approvebutton} onClick={() => handleDialogClick("approve",1)}> <ThumbU ...

What is the most efficient way to modify the variables for numerous images within a JavaScript canvas?

I'm a newcomer to using Javascript in a canvas, and coding with javascript overall. My primary goal is the following: Create numerous fireballs (images) that spawn randomly with each having a fixed y-value and random x-value. The fireballs should t ...

"The website seems to be experiencing some technical difficulties on Firefox, but I have switched to

I attempted to reset the text area after sending a message with the code below: $(document).keypress(function (e) { if (e.which == 13) { e.preventDefault(); var $form = $('#f1'); $.ajax({ url: $form.attr( ...

Issue with alignment in Bootstrap5 - ms-auto not functioning correctly in row and column components

My goal is to make the button move to the right side of the screen within the row element. I initially placed the text and button in separate column elements, and then attempted to use ms-auto on the second column element to align it to the right, but for ...

Tips for displaying files from the public folder of express 4.0 as stylized HTML rather than plain files, depending on their extensions. For example, display JSON in a formatted way,

Whenever I place a file in the "public" directory of my express folder, it automatically generates a link on my webpage. For instance, by navigating to , I can download an image. Similarly, clicking on allows me to access a JSON file without any additiona ...

When the submit button is clicked in Yii, a confirmation message will appear twice

Within my form, I included a confirmation message that displays before the save. However, the message box is appearing twice. What could be causing this issue? CHtml::submitButton('Save', array('confirm'=>'Are you sure you want ...

Choose an element on a webpage by leveraging the power of Selenium

When working with Selenium in FireFox, I encountered an issue while trying to select specific fields on a webpage. The HTML pages I am referring to are available at the following links: Sample HTML Page, another sample page. The code snippet I used is sh ...

Numerous calls for the same event

When calling two functions on the same event onChange, I noticed that the second one doesn't execute this.updateValue. As a result, the value of the input doesn't change. However, after removing the first call and changing it to onChange={this.up ...

The values are failing to update within the update panel

I have exhausted all the suggested solutions provided here in relation to my issue with no success. I am working on creating some graphs using the Dygraphs library. The JavaScript code snippet below represents just a fraction of the complete function, as I ...

What is the reason behind PHP's json_encode disregarding empty arrays?

Here is my JavaScript code that sends data to a PHP function: <script> var mydata = { id:123, name: 'mike', orders: [] }; $.ajax({ type: 'POST', ...

Issue with Jquery AJAX success function specifically in Firefox browser, while other functions in the script are functioning correctly

I have 4 scripts using ajax, but one of them isn't functioning properly in Firefox. Even the alert in success doesn't trigger anything. There are no error messages, just nothing happening. However, it works perfectly fine in IE and Chrome. Belo ...

Exploring the world of Django: Using model formsets with the power

I am struggling to use Ajax for submitting my zipped formsets. The code functions flawlessly without Ajax, but as soon as I try to incorporate Ajax, I encounter a ValidationError: [u'ManagementForm data is missing or has been tampered with'] Thi ...

Caution: The value supplied to Material-ui Autocomplete is not valid

Currently, I am working on a project using React and material-ui. While working with the Autocomplete component in my form submission, I encountered a warning. Following the basic approach provided in the documentation, here's what I tried: let Form ...

Exploring the concept of try-catch in JavaScript with a focus on the call stack within the Node

Recently, I delved into the world of Javascript and decided to explore how stack tracing functions in nodejs. Instead of looking at the source code, my lazy side led me to consult the language reference found at https://www.ecma-international.org/ecma-262/ ...

Controlling the Alignment of HTML Div Elements

I'm struggling to align some of these divs, especially centering them. I want the page to closely resemble this image: Here are the specific requirements: 1) The header text should be centered vertically and placed in a separate div with a black back ...

Improving JavaScript event management efficiency through handling numerous asynchronous HTTP requests

Summary: In a SPA CMS project, multiple dynamic data sources are causing performance issues due to a large number of asynchronous HTTP calls required to display a table with extensive data. The challenge is to maintain good performance while handling the ...

Incorporating smooth sliding animation to ng-repeat elements

Our team has developed a custom widget in ServiceNow that displays a row of icons and reveals or hides additional details in a div when icons are clicked. Below is the structure of our html and client controller: <div class="icons"> <ul class=" ...