How to fix this warning in console of a React app using the react-modal package:
Warning: react-modal: App element is not defined. Please use
Moda
Just include appElement={document.getElementById('app')}
inside your modal like this
<Modal
className="modal"
appElement={document.getElementById('app')}
>
It will work 100% if app is your central in index.html from where react loads.
Delete this attrib className="modal" and run again
If you get that warning on testing with the "react-testing-library" here is a solution: https://github.com/reactjs/react-modal/issues/576#issuecomment-524644035
using the react-testing-library (https://testing-library.com/) I get rid of that warning with:
import Modal from "react-modal";
const { container } = render(<MyComponent />);
Modal.setAppElement(container);
.... // to the testing, use Modal
or, if you want to test the modal component directly:
const { container, rerender } render(<MyModalComponent isOpen={false} />);
Modal.setAppElement(container);
// now the appElement is set we can show the modal component
rerender(<MyModalComponent isOpen={false} />);
.... // to the testing
This is my TypeScript Modal
component which wraps react-modal
v3.8.1:
import React from 'react'
import ReactModal from 'react-modal'
interface Props {
isOpen: boolean
ariaLabel?: string
}
const Modal: React.FC<Props> = ({
children,
ariaLabel = 'Alert Modal',
isOpen,
}) => (
<ReactModal
appElement={document.getElementById('root') as HTMLElement}
ariaHideApp={process.env.NODE_ENV !== 'test'}
isOpen={isOpen}
contentLabel={ariaLabel}
testId="modal-content"
>
{children}
</ReactModal>
)
export default Modal
Usage in component with state = { isOpen: true }
:
<Modal isOpen={this.state.isOpen}>
<p>
Modal Content here…
</p>
<button onClick={() => { this.setState({ isOpen: false }) }}>Okay</button>
</Modal>
just put this Modal.setAppElement('#root'). this will solve the warning. the root element coming from inside public folder index.html.
The shortest solution is to add
appElement={document.getElementById("hereIsYourRootElementId")}
It lets react-modal know where is your root element. It is not required, but recommended.