cssreactjsinputjsxconditional-rendering

Input element is not displaying


In my React app, I am trying to create logic for how my input elements should be displayed. I used the window.innerWidth for different screen sizes, as is seen below:

<div className='Trends'>
        <div>
          <h4 className='trend-head'>TRENDING ITEMS</h4>
        </div>

        {window.innerWidth < 991 ? ( 
            <div className='input-arrow'>
            <input type="text" placeholder={selectCategory || 'All'} className='trend-input' />
            <BiSolidDownArrow className='dr-arrow' onClick={() => setShowArray(!showArray)} />
            
          </div>
          
        ) : (
          <div className='Array-div'>
            <ul>
              {storedArray}
            </ul>
          </div>
          
          
        )}
      </div>
   
  );

However, it is not displayed. I have gone to inspect my browser's console, and the input div is not even showing alongside other divs.


Solution

  • The issue is that the code will run only once when the component is mounted, and at that moment window.innerWidth is equal to 0 so the input will never get shown. Instead, use the useState hook to handle changes in state and re-render accordingly. Finally, use useEffect to add an eventListener to the window to listen to the resize event and toggle states.

    import { useState, useEffect } from "react";
    import { StrictMode } from "react";
    import { createRoot } from "react-dom/client";
    
    function App() {
        const [smallWindow, setSmallWindow] = useState(false);
    
      useEffect(() => {
        if (window.innerWidth < 400) {
          setSmallWindow(true);
        } else {
          setSmallWindow(false);
        }
        const resizer = () => {
          if (window.innerWidth < 400) {
            setSmallWindow(true);
          } else {
            setSmallWindow(false);
          }
        };
        window.addEventListener("resize", resizer);
        return () => {
          window.removeEventListener("resize", resizer);
        };
      }, []);
    
      return (
        <div className="App">
          <p>Resize this window to see the text change below</p>
          {smallWindow ? <h1>small screen</h1> : <h1>BIG SCREEN</h1>}
        </div>
      );
    }
    
    const rootElement = document.getElementById("root");
    const root = createRoot(rootElement);
    
    root.render(
      <StrictMode>
        <App />
      </StrictMode>
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
    <body>
        <div id="root"></div>
    </body>