“Warning: react-modal: App element is not defined. Please use `Modal.setAppElement(el)` or set `appElement={el}`”

后端 未结 12 1260
轻奢々
轻奢々 2021-02-07 03:36

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

相关标签:
12条回答
  • 2021-02-07 04:24

    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.

    0 讨论(0)
  • 2021-02-07 04:26

    Delete this attrib className="modal" and run again

    0 讨论(0)
  • 2021-02-07 04:28

    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
    
    0 讨论(0)
  • 2021-02-07 04:30

    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>
    
    0 讨论(0)
  • 2021-02-07 04:30

    just put this Modal.setAppElement('#root'). this will solve the warning. the root element coming from inside public folder index.html.

    0 讨论(0)
  • 2021-02-07 04:37

    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.

    0 讨论(0)
提交回复
热议问题