skip to Main Content

I am looking for a solution to call different functions as per orientation

if (window.innerHeight > window.innerWidth) {
  alert("You are in portrait mode");
  <Portrait />
}

if (window.innerHeight < window.innerWidth) {
  alert("You are in landscape mode"); 
  <Landscape />
}

Written the following functions

export default function Landscape() {
  return (
    <main>...</main>
  );
}

function Portrait() {
  return (
    <main>...</main>
  );
}

Problem

  • Every time, only Landscape function getting called (I understand because I mentioned default)
  • Atleast, I was expecting Portrait function to be called, when device in portrait mode

Please help to get it done

2

Answers


  1. import React, { useState, useEffect } from 'react';
    
    function Landscape() {
     return (
       <main>
       <h1>Landscape Mode</h1>
       {/* Your landscape content */}
       </main>
     );
    }
    
    function Portrait() {
     return (
      <main>
      <h1>Portrait Mode</h1>
      {/* Your portrait content */}
     </main>
    );
    }
    
     export default function App() {
       const [isLandscape, setIsLandscape] = useState(window.innerWidth > window.innerHeight);
    
     useEffect(() => {
      function handleResize() {
      setIsLandscape(window.innerWidth > window.innerHeight);
      }
    
      window.addEventListener('resize', handleResize);
      return () => window.removeEventListener('resize', handleResize);
     }, []);
    
     return (
       <div>
      {isLandscape ? <Landscape /> : <Portrait />}
       </div>
    );
    

    }

    Login or Signup to reply.
  2. You can also use this custom hook.

    It utilizes the new screen.orientation feature instead of checking innerHeight / innerWidth.

    As of March 2023, it works across the latest devices and browser versions.

    import { useOrientation } from 'react-use';
    import './App.css';
    
    const PortraitContent = () => {
        return (
            <div>
                <h1>Welcome to the portrait mode</h1>
                <p className="content-portrait">Here is some information that's
                    specific to portrait mode</p>
            </div>
        );
    }
    
    const LandscapeContent = () => {
        return (
            <div>
                <h1>Welcome to the landscape mode</h1>
                <p className="content-landscape">Here is some information that's
                    specific to landscape mode</p>
            </div>
        );
    }
    
    const App = () => {
        const { type } = useOrientation();
        return (
            <div>
                {type === 'landscape-primary' ? (
                    <LandscapeContent />
                ) : (
                    <PortraitContent />
                )}
            </div>
        );
    }
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search