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.
The issue is that the code will run only once when the component is mounted, and at that moment
window.innerWidthis equal to0so the input will never get shown. Instead, use theuseStatehook to handle changes in state and re-render accordingly. Finally, useuseEffectto add aneventListenerto the window to listen to the resize event and toggle states.