Skip to content

Body class not removed under certain circumstances #888

Open
@Plygon

Description

@Plygon

Summary:

If React Modal is mounted and almost immediately unmounted, the body's class is not removed when the modal disappears. If this class is used to prevent scrolling, the body will remain unscrollable forever.

Steps to reproduce:

  1. Create a project using React Modal.
  2. Add the following component somewhere on the page:
import React, { useEffect, useState } from 'react';
import Modal from 'react-modal';

export const Flash = () => {
   const [hide, setHide] = useState(0);

   useEffect(() => {
       if (!hide) {
           setHide(true);
       }
   }, [hide])

   return <>
       {!hide && <Modal isOpen={true}>
           <div>
               Modal text.
           </div>
       </Modal>}
       Other text
   </>
}
  1. Load the page and inspect the body element. Note that it still has the class ReactModal__Body--open even though no modal is open.

Expected behavior:

The body element should not have the class ReactModal__Body--open.

Link to example of issue:

https://codesandbox.io/s/react-modal-unmount-bug-duvib?file=/src/App.js

Additional notes:

This is happens because the example component is unmounting the modal immediately in a useEffect. This causes it to unmount after componentDidMount is called, but before ModalPortal's setState takes effect. So when componentWillUnmount is called on ModalPortal, it does not yet have the open state, so it does not decrement the counter of the className.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions