javascriptreactjsdevice-orientation

Calling functions as per device orientation


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

Please help to get it done


Solution

  • 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>
    );
    

    }