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

Despite implementing componentDidMount, the setState function is failing to update an initialized array state property

I have checked out similar questions such as : Why isn't this.setState updating the state property? Issue with this.setState not updating state Understanding that setState operates asynchronously is key. This snippet showcases my code: import Rea ...

Execute a jQuery function every time the class of the parent container div changes

I am seeking to trigger the function below whenever its containing div parent <div class="section">...</div> transitions to an "active" state, for example: <div class="section active">...</div> $(".skills-grid__col").each(function ...

Why isn't the show/hide feature in Jquery functioning properly?

I have a div that needs to be displayed after hovering over another element. These elements are not within the same div. The popup info should appear when an icon with the class .option_36_124 is hovered over. $(".option_36_124").hover(function(){ $(& ...

Highlight and trim lengthy text using React

Imagine I have a lengthy text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo con ...

Encountering a circular structure while attempting to convert to JSON -- starting at an object created by the 'HTMLInputElement' constructor

I have been trying multiple solutions to fix this issue, but I'm still struggling to resolve it. My application is built using Next.js and I am using axios as the HTTP client. import React, {useState} from 'react' import axios from 'axi ...

Adjust the button's color even after it has been clicked

My goal is to update the button's color when it's clicked. I found some examples that helped me achieve this, but there's an issue - once I click anywhere outside of the button, the CSS class is removed. These buttons are part of a form, and ...

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

Tips for showcasing images retrieved from a REST API on the frontend, with the condition that only one image should be displayed using multer

I am experiencing an issue where only the image logo is being displayed in my frontend, rather than the entire image that I uploaded in string format on my backend. Can someone please help me troubleshoot this error and identify what may be wrong with my c ...

What steps can I take to make Accounts.onLogin have an effect on my Meteor React ES6 application?

Is there a way for my meteor app to trigger setState in the App component upon login and logout events? How can I make changes within one section of code, like Accounts.onLogon, affect another component, such as App{}? Additionally, how can logouts be de ...

Is Swiper carousel navigation secretly operating without being seen?

I've got a website that utilizes the Swiper carousel from SwiperJS, find it here: An issue I am facing is that the navigation elements are invisible but functional, with the pagination feature unaffected. This peculiar behavior is observed only in Sa ...

When the anchor tag is clicked, I'm displaying the DIV for Customer Testimonials, however, the expansion of its height is not

One way to display customer testimonials is by using flexslider to create a horizontal scroll. The testimonials are hidden and only shown when the "view all testimonials" link is clicked, which can be seen in this JSFiddle example: Working : Demo JQuery ...

The delete button in the "Chip" component of React Material-UI is not functioning as expected

I'm having trouble with the "Chip" control and its "X" button functionality. Unlike the examples shown here: http://www.material-ui.com/#/components/chip Adding the "onRequestDelete" property does include the "X" button, but it doesn't respond t ...

Issues with array visualization when rendering within a table using the map function, despite successful logging in

I have encountered an issue with rendering the personnel array data in a table inside my parent component. Despite successfully logging the data using console.log(personnel), I am unable to render it using the map function within the table. Even attempting ...

Transfer or duplicate an SVG image from the bottom div to the top div

Is there a way to move a div from the chart_div to the movehere div? I've tried duplicating it below the current svg, but I'm having trouble targeting just the header row ('g' element) specifically. Here is the HTML: <script type= ...

Encountered an error while attempting to install the @typescript-eslint/eslint-plugin

After starting the installation process for eslint plugins, I encountered an issue with @typescript-eslint/eslint-plugin. The plugin requires installation using--legacy-peer-deps, but this approach may introduce potential bugs by accepting an incorrect an ...

The Material-UI datepicker seems to be malfunctioning

I've come across an issue with the material-UI date picker not functioning correctly. I am using material-UI and Reactjs, but unfortunately, it's not working as expected. Can someone please assist me in resolving this problem? const minDate ...

The QR code disappears from the screen once the button is no longer pressed

After following an online tutorial on creating a QR code generator, the code works fine and I am able to display the image. However, I'm facing an issue where the image disappears from the screen once the button is released. Here is the code snippet: ...

The width property is not being passed down to the table

I'm experiencing difficulties with the scaling of my body content. When the page is initially opened, it scales to 100%. However, when I resize the screen to make it wider, the content gets bigger but when I try to make it smaller again, it remains a ...

Sharing data from a Provider to a function in React can be done through various methods

After developing an NPM library that contains various utility functions, including one for calling endpoints, I encountered a roadblock when trying to set the Axios.create instance globally. Initially, my idea was to create a Provider and establish a cont ...

Customize the text color across all sections of the application in ExtJS 6

I am looking to update the text color across my entire application. Currently, it's gray and I would like to change it to black. The platform I am working with is classic. I came across this code snippet in CSS: .x-body { margin: 0; -webkit-f ...