Cannot build P5 sketch in React. WebpackError: ReferenceError: window is not defined

I’ve got a p5.js sketch that is included in my React project. When I build my project it throws:

  • error "window" is not available during server side rendering.
  • on: window.requestAnimationFrame = (function() {
  • WebpackError: ReferenceError: window is not defined

Ok, I understand why. During the build the window DOM is not available. So I tried to work around it with two ways, as seen in my code example.

  • First is to use react loadable componant
  • Second to check if window is undefined (on build) and if so return something else than the main code.

my code example:

  import loadable from '@loadable/component'
  import sketch from "./p5_app";
  
  class GetP5Wrapper extends React.Component {
    render() {
  
      if (typeof window === 'undefined') 
         return <span>loading...</span>
  
      const P5Wrapper = loadable(() => import('react-p5-wrapper'))  //loadable help is not to run on build
  
      return <P5Wrapper sketch={sketch}/>
    }
  }

#the question:#
How do I get my sketch to only run on client side.