The input field is failing to show up on the screen

I have been working on my React app and experimenting with how to dynamically display input elements based on different screen sizes. To achieve this, I implemented the use of window.innerWidth as shown in the code snippet 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>
   
  );

Despite implementing this logic, it seems that the input div is not being displayed correctly. Upon inspecting my browser's console, I noticed that the input div is missing when compared to other div elements on the page.

Answer №1

The problem arises from the fact that the code only executes once when the component is initially mounted. At that point, window.innerWidth is 0, causing the input to never appear. To address this issue, it is recommended to utilize the useState hook for managing state changes and triggering re-renders accordingly. Additionally, leverage the useEffect hook to set up an eventListener, which will monitor window resize events and toggle states accordingly.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for transmitting information from a page to layout components using the NextJS 13 app router?

Currently, I am facing difficulties in transferring data from a child component to a layout component. My main struggle lies in dynamically rendering a "title" in the layout component. Here is a simplified version of the issue at hand. I am making use of t ...

Prevent a HTML button from being clicked multiple times before it disappears (using Django)

I am currently working on a Django project that involves events where users can join by adding their user_id and event_id to the attend model. On the event page, there is a join button form that, when clicked, adds the user to the attendees list. After cli ...

What is the best way to input information into my Google spreadsheet with React JS?

After using https://github.com/ruucm/react-google-sheets as a reference, I encountered a persistent gapi 404 error whenever I tried to run the code. It seems like the GitHub link might not exist, causing my app to fail. However, I could be mistaken. Is t ...

Rotation of the SVG coordinate system distorts angles

My comprehension of SVG, particularly the viewport, viewBox, and the user coordinate system, seemed fairly solid. In the initial example provided below, we utilized a viewBox with a matching aspect ratio as the viewport. As expected, there was no distorti ...

Desktop media queries are functioning properly, yet experiencing issues on mobile devices

I've come across this same question multiple times, but the solutions I've found so far haven't been helpful. My media queries are working perfectly on desktop, but they don't seem to take effect on three different android devices. It&a ...

Passing a ref from a parent component to a child component in reactjs

I have the following situation, how can I make sure that the attachment field in the child component is accessible from the parent component? class ServiceDeskCustomerCreate extends Component { constructor(props, context) { super(props, context); ...

React is throwing an error message stating that setCount is not a valid function

Getting an error saying setCount is not a function. I am new to this, please help. import React, { memo, useState } from "react"; export const Container = memo(function Container() { const { count, setCount } = useState(0); return ( ...

Font formatting functions correctly on local host, but fails to load on live server

I've successfully integrated the Google font "Raleway" into my Next.js application. However, I'm facing an issue where the fonts display correctly on my local server but do not show up in the live environment after running npm build. Any advice ...

Eliminate perfect-scrollbar functionality on mobile devices

I have applied the perfect-scrollbar class with 'height: auto' on mobile screens, expecting it to work properly. It's functioning well in responsive mode on the web. However, it does not scroll on mobile devices. @media (max-width: 992px) { ...

What is the purpose of the 'offset' property in React Native's PanResponder?

TL;DR: Seeking clarity on the implementation of Panresponder code in React Native, specifically questioning the necessity of using the 'offset' value alongside the animated value. Full Question: The Situation: In my React Native project, I am ...

HTML5 header video with a subtle color palette

Is there a way to insert a muted video in the header that spans the full width but only has a height of 300px? The issue I am encountering is that when I decrease the height of the video, the width automatically decreases as well. However, what I want is ...

Exploring Next.js: The difference between Client Side Navigation and direct html modifications

Currently, I am diving into the next.js tutorial, but there are some aspects that have me puzzled: In the tutorial, it mentions here, that when you click a <Link> element, it does not trigger a server request but instead performs "Client-side naviga ...

Trouble with ASP.NET Master Page CSS Rendering Incorrectly

My CSS seems to be causing some trouble as the DIVs are not aligning as they should. Instead, they are just wrapping around the text and not adjusting the page layout properly. Here is an example of my CSS: body { height: 95%; width: 100%; ma ...

Error: The selector "html" is not considered pure as it does not contain any local class or id. Pure selectors must include at least one local class or id

When working on my Next.js project, I included the following code in _app.js: import '../src/styles/style.module.scss'; import '../src/styles/main.module.scss'; This is the content of main.module.scss: // ./src/styles/main.module.scss ...

Error in Node: resolve-url-loader - CSS resolution error

Trying to set up a React project as the development server on my Surface has been causing issues, unlike when I run the same configuration on my PC. Despite trying to replicate the same conditions, the problem persists. The error message received is: ./s ...

Initiate the React project by executing the command to start React Native development

Typically, I start my projects using npm start, but one time I accidentally ran npx react-native start and all the installation process for React Native completed. Now, I'm not sure if I need to worry about this or if I should remove React Native. If ...

Error: The function props.addToCart is not accessible

While attempting to trigger my action on the client's click of the "addToCart" button to add a new product to the cart, I encountered the error message: "TypeError: props.addToCart is not a function." I am relatively new to Redux and have grasped the ...

Checking for an exact value using the includes() method in JavaScript - a comprehensive guide

In order to populate checkboxes based on a string delimited with pipes, I have been using the includes() method. However, I am encountering an issue where items with similar names are both marked as true because they share the same string, even if they are ...

Dynamic JavaScript tool

Does anyone know which library is being used on the website linked here? I am working on a project similar to this and would appreciate if anyone can identify this library for me. Thank you in advance. ...

Autofocus on the first MenuItem with the same value in ReactJS MUI

I am trying to set up a select menu that displays a list of languages, with the most commonly used ones at the top. Here is an example snippet of the code: <Select value={language} onChange={e => setLanguage(e.target.value)} > <MenuItem v ...