title: React execute script if window width
body: <p>I have a button in React that executes a function onClick. I want to get rid of the button, and instead programmatically execute the function if window width &lt; 1000px.</p>
  
  <p>A restriction is that I can not add a plugin.</p>
  
  <p>Here's what the code looks like...</p>
  
  <pre><code>// Do I need useState, useEffect?
  import React, { PureComponent } from "react";
  
  class MainNav extends PureComponent {
  state = {
    // Does something go here? What goes here and how do I use
    // state to execute the function?
    navIsCollapsed: false,
  };
  
  // this controls rendering of huge images
  toggleShowImages() {
    this.setState({
      navIsCollapsed: !this.state.navIsCollapsed,
    });
  }
  
  // I want this to be executed by width &lt; 1000
  handleSideNavToggle = () =&gt; {
    this.toggleShowImages(); // controls if React renders components
    document.body.classList.toggle("side-nav-closed");
  }
  </code></pre>
  
  <p>Here's render the button that's currently executing the function.  I want width &lt; 1000 to programmatically execute its function.</p>
  
  <pre><code>// window width &lt; 1000 should execute this function
  &lt;div onClick={this.handleSideNavToggle}&gt;Don't render huge images&lt;/div&gt;
  
  // here are the images the function conditionally renders
  &lt;should show images &amp;&amp; 
    &lt;div&gt;Massive huge image&lt;/div&gt;
    &lt;div&gt;Massive huge image&lt;/div&gt;
    &lt;div&gt;Massive huge image&lt;/div&gt;
  &gt;
  </code></pre>
  
  <p>I could use CSS media query to show or hide the massive images I don't want, but that's horrible use of React. </p>
  
  <p>I've looked and tried to implement similar questions on SO that either invoke plugins, are out of date, or the use case is too different (for example, "re-render everything based on screen size"). I've also tried to React-ify vanilla javascript. This seems like it ought to be simple to do but I can't make it work.</p>
  
  <p>Any React wizards out there who can answer with a clean, efficient solution?  </p>