Home > Net >  How to use .slice with media query
How to use .slice with media query

Time:11-29

I'm trying to slice objects whenever the screen is 600px and down, I'm using this code in react to know if the screen is 600px or down

  const [matches, setMatches] = useState(
    window.matchMedia("(max-width: 600px)").matches
  )

  useEffect(() => {
    window
    .matchMedia("(max-width: 600px)")
    .addEventListener('change', e => setMatches( e.matches ));
  }, []); 

I'm trying to show pictures

return (
    <div className="shopsHomeFeedImgsCont">
      {shops.map((shop) => (

        <img className="shopsHomeFeedImgs"
        src={shop.shopPic} />
        
      )).slice(0, 2)}
    </div>
);

My question is how slice(0, 2) only when the screen is 600px and down?

CodePudding user response:

You can use your matches state to make your shops data depend on the match query result.

const shopsToBeRendered = matches ? shops.slice(0, 2) : shops;

return (
    <div className="shopsHomeFeedImgsCont">
      {shopsToBeRendered.map((shop) => (
        <img className="shopsHomeFeedImgs" src={shop.shopPic} />
      ))}
    </div>
);
  • Related