Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use .slice with media query

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading