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;
}
}