Search code examples
reactjsfullscreen

how to apply Full screen striction in react js?


Here i am developing an examination system. I want to apply full screen when i launch exam component. While doing student strict to remain in full screen. When he/she exit from full screen then automatically call a function to save exam result.


Solution

  • There are some limitations when it comes to displaying things fullscreen but I suggest you to use https://github.com/sindresorhus/screenfull.js . It's quite well maintained and makes it easier for you to support multiple browsers.

    In React you could do something like this:

    // import/exports depend on your setup, this is just an example
    const screenfull = require('screenfull');
    
    class MyComponent extends React.Component {
      componentDidMount() {
        if (screenfull.isEnabled) {
          screenfull.on('change', () => {
            console.log('Am I fullscreen?', screenfull.isFullscreen ? 'Yes' : 'No');
          });
        }
      }
    
      // enabling fullscreen has to be done after some user input
      toggleFullScreen = () => {
        if (screenfull.isEnabled) {
          screenfull.toggle();
        }
      }
    
      render() {
        return (
          <button onClick={this.toggleFullScreen}>Toggle fullscreen</button>
        )
      }
    }
    

    LE:

    To detect a fullscreen change you can use the screenfull.on('change') event: https://github.com/sindresorhus/screenfull.js#detect-fullscreen-change

    Added code for this in the above example.