Home > Software design >  Conditionally render component views based on browser screen size
Conditionally render component views based on browser screen size

Time:04-30

I have three different components representing different views for screen sizes. I want to render one of them based on the browser view width. I've managed to get this working using ternary operators, but it'll only work with two elements.

Can someone let me know how to accomplish this without having to use display: hidden on one of the elements?

Here is my code so far:

import React, { useState, useEffect } from "react";
import Navbar from "../../shared/components/Navbar/Navbar";
import Page from "../../shared/interface/Page/Page";

{/* elements */}
import DesktopView from "../../home/components/DesktopView/DesktopView";
import MobileView from "../../home/components/MobileView/MobileView";
import TabletView from "../../home/components/TabletView/TabletView";

function Home() {
  const [isDesktop, setDesktop] = useState(window.innerWidth > 650);
  const [isTablet, setTablet] = useState(window.innerWidth > 768);
  const [isMobile, setMobile] = useState(window.innerWidth > 640);

  const updateMedia = () => {
    setDesktop(window.innerWidth > 1024);
    setTablet(window.innerWidth > 768);
    setMobile(window.innerWidth > 640);
  };

  useEffect(() => {
    window.addEventListener("resize", updateMedia);
    return () => window.removeEventListener("resize", updateMedia);
  });

  return (
    <Page>
      <Navbar />

      {/* Elements should go here */}
    </Page>
  );
}

export default Home;

CodePudding user response:

You can try following Code instead of ternary

isDesktop && <DesktopView />
isTablet && <TabletView />
isMobile && <MobileView />

So if isDesktop is true then only DesktopView will render and similarly isTablet will control TabletView and isMobile will control MobileView rendering

  • Related