I imported two images ( IMG
and IMG2
). The IMG is assumed to be displayed when the viewport width is less than 600px, and another one is displayed if the viewport width is greater than or equal to 600px. So I added a function that checks the viewport width and then it returns one of those two images, but the problem is that it only returns the first image I put in the function, which is IMG
. Even if the viewport width becomes larger than 600px, it still shows IMG instead of IMG2. Note: I can solve this problem by just using media queries and setting display to None, but I would like to know how to solve this problem using React.
Link to all my code in 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; } }
To do this with React, you need to attach to the document resize event.
Below is a simple example that changes the text and background color on resize.