niina
niina

Reputation: 119

How to put modal dialog in fullscreen mode using react?

I have to display an element in full screen mode on clicking a button. This works. However, it doesn't render the modal dialog in full screen mode. This is because this modal dialog is an element that is added at the other div named modal_root and this content div is not rendered in dom. How can I make sure that this modal dialog is also rendered in full screen mode?

Below is the code,

<body>
    <div id="root">
        <div class="content"></div>
    </div>
</body>

On clicking on the fullscreen button i call the below method.

open_content_fullscreen = () => {
    let elem = document.querySelector('.content');
    if (elem.requestFullscreen) {
        elem.requestFullscreen();
    }
}

Now when i click some button say "edit" it opens the modal dialog which is the element that is rendered at the div with class modal_root and content div is not seen in the dom something like below,

<body>
    <div id="root">
        <div class="modal_root">
            <div class="dialog"></div>
        </div>
    </div>
</body>

How can i fix this. could someone help me with this. Thanks.

Upvotes: 3

Views: 6929

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30390

When interacting with the DOM directly from a React component, you'll typically want to do so via a ref.

This means that you should call requestFullscreen() via the DOM element provided by a component ref, rather than the result returned from querySelector().

So for instance, you could refactor your code to follow a pattern like this:

/* An example "root component" */
class RootComponent extends React.Component {

  constructor(props) {
    super(props);

    /* Create a ref to the div that we want to access DOM element of */
    this.fullscreenModal = React.createRef();
  }

  openContentFullscreen = () => {    
      /* let elem = document.querySelector('.content'); */

      /* Access the element of "full screen" div: */
      const elem = this.fullscreenModal.current;

      /* Interact with it as a normal DOM element: */
      if (elem.requestFullscreen) {
          elem.requestFullscreen();
      }
  }

  render() {

      return <div>
        <button onClick={this.openContentFullscreen}>Open Fullscreen</button>

        <div ref={this.fullscreenModal}>
            Hello fullscreen world!
        </div>
      </div>
  }
}

For more information on refs, see this documentation - hope that helps!

Upvotes: 1

Related Questions