There are two kinds of Images that I have imported ( IMG
and IMG2
). IMG suppose to be displayed when the viewport width is less than 600px and the other one would be displayed if the viewport is bigger or equal to 600px. So I added a function to check the viewport width then it returns one of these two images, but the problem is that it's only returning the first that I put in the function, which is the IMG
. even when viewport width becomes bigger than 600px it's still displaying IMG instead of IMG2. Note: I can solve this by only using media queries and setting display to none but I would like to know how to do it with 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;
}
}
CodePudding user response:
To do this with React, you going to want to attach to the documents resize event.
Below is a simple example, that changes text & background color when resizing.
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>