The function within the React component is failing to produce the expected output

After importing two types of images (IMG and IMG2), I wanted to display IMG when the viewport width is less than 600px, and IMG2 when it's equal to or greater than 600px. I created a function to determine the viewport width and return the respective image, but I'm facing an issue where it always displays IMG regardless of the viewport size reaching 600px. Although I can use media queries to solve this by setting display to none, I prefer to find a solution using React.

To view all my code on Github: https://github.com/IssamAth/PerfumeProduct.com

import IMG from '../../assets/image-product-mobile.jpg'
import IMG2 from '../../assets/image-product-desktop.jpg'

const ProductImage = () => {
  function displayImage(){
    let vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
    console.log(vw);
    if(vw < 600) {
     console.log(vw + "is smaller than 600");
     return (<img src={IMG} alt="" />);
    } else {
     console.log(vw + "is bigger than 600");
     return (<img src={IMG2} alt="" />);
    }
}
  return (
    <div className='container-img'>
      {displayImage()}
    </div>
  )
}

export default ProductImage
.container-img img {
    height: 15rem;
    width: 100%;
    background: white;
    border-radius: 0.8rem 0.8rem 0 0;
}

.container-img {
   
}

 /* -----------------for bigger phones------------------- */

@media screen and (min-width: 390px) {
    .container-img img {
        height: 20rem;
    }
}


Answer №1

If you want to achieve this in React, you need to listen for the document's resize event.

Check out this straightforward example below, where the text and background color change as you resize the window:

const {useEffect, useState} = React;

const getWidth = () => document.documentElement.clientWidth;

const ResizeCheck = () => {
  const [width, setWidth] = useState(getWidth());
  useEffect(() => {
    const resize = () => setWidth(getWidth());
    window.addEventListener('resize', resize);
    return () => window.removeEventListener('resize', resize);
  }, []);
  return <div>{
    width >= 600 
      ? <div
        style={{backgroundColor: 'pink'}}
      >Greater than equal to 600</div>
      : <div style={{backgroundColor: 'yellow'}}>Less than 600</div>
    }
  </div>;
}

const root = ReactDOM.createRoot(document.querySelector('#mount'));
root.render(<ResizeCheck/>);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

<div id="mount"></div>

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

Discovering data in individual tr elements within a table with jQuery by utilizing .text()

I'm currently working on a project where I need to separate the three table rows within a dynamically generated table. My goal is to have jQuery treat each row individually in order to extract specific values like price and SKU. You can see an example ...

Is there a way to create a bar chart that begins at the 0 point of the y-axis instead of starting from the base of the SVG?

Is there a way to start the bar chart from the 0 point of the y-axis instead of the very bottom of the svg? How can I achieve this? let url = "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json"; const padding = 5 ...

Can someone guide me on how to retrieve data from a MUI table within a React project

Currently, I am retrieving data from a server in JSON format and looping through this data to display specific information. Everything is functioning as expected, but I'm encountering an issue with a Popover element that contains items with onclick ev ...

hiding an "input type="file" element by using a button to conceal it

Is it possible to create a button that triggers file upload functionality? I couldn't find any solutions on Google. I've heard it can be done with labels, but I specifically need to use a button for better UX/UI. <button style="position:fixe ...

What is the best method for opening .xls files using ExcelJS?

I am facing an issue with accessing a .xls file using the ExcelJS library. Interestingly, there are no issues when it comes to reading .xlsx files. Previously, I relied solely on the xlsx js library and never encountered any problems while accessing .xls f ...

Display a few HTML elements sourced from a different online platform

I am trying to extract a specific value from a span element on another website and render it on my own website using either a GET/FETCH request or some other method. Currently, I have this code but I am struggling to extract the data I need. The data I am ...

Enhance your Django webpage with real-time updates using AJAX technology

[Revised for Clarity and Detail] The challenge I'm facing is related to the architecture of my project. I have multiple ideas on how to achieve my goal, but I'm stuck on identifying the correct or most efficient approach. To provide more context ...

Save React code as a single HTML file

My current project involves creating one-page websites for a specific service that only accepts single inline HTML files. To make these webpages as modular as possible, I am utilizing React to create ready components. The challenge is exporting the final R ...

Maintaining the integrity of Jquery Tab even after refreshing the page is essential

I recently started using Jquery and encountered an issue with tab implementation. Whenever I refresh the page, it automatically directs me back to the initial tab setting. $(function() { var indicator = $('#indicator'), i ...

Encountering a problem with npm during the installation of a package in a

Every time I attempt to install an npm package, I encounter a particular error message that causes the installation process to come to a halt. Below is the exact error message: Error Message: This npm version is designed for lockfileVersion@1, however, ...

Tips for concentrating on the initial input field produced by an ng-repeat in AngularJS

Currently, I am dynamically generating input fields using ng-repeat and everything is working smoothly. However, my requirement is to set focus on the first input that is generated by this ng-repeat based on their sequenceId values. So far, I have attempte ...

Deleting a DOM element within an element that has been created by an external script

On a webpage, I have third-party ad content that is generated by an external script. This content has a delay in loading. My goal is to eliminate a line break from the ad content, but this can only be done once the external script finishes loading and all ...

Is the .html page cached and accessible offline if not included in the service-worker.js file?

During the development of my PWA, I encountered an unexpected behavior with caching. I included a test .html page for testing purposes that was not supposed to be cached in the sw.js folder. Additionally, I added some external links for testing. However, w ...

How to implement an Angular Animation that is customizable with an @Input() parameter?

Have you ever wondered if it's possible to integrate custom parameters into an Angular animation by passing them through a function, and then proceed to use the resulting animation in a component? To exemplify this concept, consider this demo where t ...

Nested state fails to display HTML content or activate controller initialization

I am trying to utilize ui-router's parent/child states with the code snippet below. Everything seems to be in order as there are no console errors, but for some reason the HTML content is not being rendered and the controller's init function is n ...

Circular picture contained within a Bootstrap column on an irregularly-shaped image file

I am looking to create a circular effect for an image that is originally rectangular, resembling a typical profile picture. I have come across several sources on how to do this. The challenge arises in trying to achieve this effect within a bootstrap colu ...

Determine in Node.js whether an image is empty or not

I am in the process of developing a testing application that generates an image based on the URL provided by the user. The screenshots are captured using phantomJS and nightmareJS. Occasionally, users may input a non-existent URL, resulting in a blank ima ...

Exploring Ancestors with Jquery to Find Input Fields

In my current project, I am working on a function that needs to extract the values from two input fields within a specific div element. These values will then be added to an array and posted as JSON data. However, I am facing difficulties in navigating thr ...

Determine the number of XML elements and display the results for each XML element counted

I need assistance with a problem I am facing. I am extracting data from an XML API using PHP. Below is my code snippet: <?php $gigatools = simplexml_load_file('http://gigs.gigatools.com/u/A2LTD.xml'); echo "<table id='gigs_parse&apos ...

Tips for avoiding duplicate Id tags while using Ajax in MVC

Hello everyone, I am curious to learn about the precautions and techniques you employ when working with Ajax or MVC functions such as @Html.Action in order to effectively manage and prevent duplicate Ids for Html tags. In addition, how does the page handl ...