I wouldike to remove or hide an image when I run the application in mobile version or if max-width is set :
<ImageWrapper key={image.src}>
<img src={getImageUrl(path, image.src)} srcSet={getSrcSet(path, image.src)} alt={image.alt} />
</ImageWrapper>
try these two steps:
className to your component as follow:<ImageWrapper key={image.src} className="YourClass">
<img src={getImageUrl(path, image.src)} srcSet={getSrcSet(path, image.src)} alt={image.alt} />
</ImageWrapper>
display parameter based on screen size in your CSS file:.YourClass {
display:block;
/* other properties */
}
@media only screen and (max-width: 768px) {
.YourClass {
display:none;
}
}
You can get the width of the content in javascript if you like to do this in javascript for some reason.
cons: you have to populate your code with aditional javascript
pro: if the user is using only mobile, it will not request the image which is good to prevent aditional requests. If you use css display:none it will request the image anyway.
import { useState, useEffect } from 'react';
//
const [width, setWidth] = useState(window.innerWidth);
// method to update the width size
const handleWindowSizeChange = () => {
setWidth(window.innerWidth);
};
// create a eventListener to update the width every time the user resize the window
useEffect(() => {
handleWindowSizeChange();
window.addEventListener('resize', handleWindowSizeChange);
return () => {
window.removeEventListener('resize', handleWindowSizeChange);
};
}, []);
Now you can use the width to check the size and check if the size is mobile or not.
if(width < 700) { // isMobile }
TIP: Hide the image in the render:
{width < 700 && <img src="image.jpg" />}