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
Some solutions are given in react-modal issue #133:
The problem lies here: Depending on when it evaluates react-modal@1.6.5:/lib/helpers/ariaAppHider.js#L1:
undefined || null
. Modal.setAppElement()
is called with null
or not called at all with the <script />
placed on <head />
(same as above). selector
that does not match any results.@yachaka snippet prevents this behavior by defining the element before placing the <Modal />
:
componentWillMount() {
Modal.setAppElement('body');
}
@ungoldman answer, if you don't want to depend on `setAppElement':
Inject the bundled application JS into
<body>
instead of<head>
.
Though ideallyreact-modal
should wait until the DOM is loaded to try attaching todocument.body
.
If rendering on server-side, you must provide a
document.body
, before requiring the modal script (perhaps it should be preferable to usesetAppElement()
in this case).
Update:
react docs have been updated to include the information above, so they should now be clearer for users running into this issue.
react-modal issue #567: add information (from issue #133 linked above) to the docs.
you need to add # before your root element id.
import React from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root');
const OptionModal = (props) => (
<Modal
isOpen={!!props.selectedOption}
contentLabel='this is the selected option'
>
<h3>Selected Option</h3>
{props.selectedOption && <p>{props.selectedOption}</p>}
<button onClick = {props.handleCloseOptionModal}>Close</button>
</Modal>
);
export default OptionModal;
here is the reference: http://reactcommunity.org/react-modal/accessibility/
we can use ariaHideApp={false} additional property.
<Modal isOpen={true} ariaHideApp={false}>
//code
</Modal>
this solution worked for me.
For reference, since it was a pain for me, if you are doing SSR, use the following code to prevent errors server-side:
if (typeof(window) !== 'undefined') {
ReactModal.setAppElement('body')
}
You could put this in componentDidMount()
anywhere you use a modal or I put it in a custom modal component so it's nice and DRY.
Add ariaHideApp={false}
to Modal
attributes.
This should work:
<Modal isOpen={!!props.selectedOption}
onRequestClose={props.clearSelectedOption}
ariaHideApp={false}
contentLabel="Selected Option"
>
</Modal>
If getting the Warning: react-modal: App element is not defined...
error when running tests (we were running Jest), you can suppress the warnings by adding the following to your test file:
import ReactModal from 'react-modal';
ReactModal.setAppElement('*'); // suppresses modal-related test warnings.