Skip to content

Instantly share code, notes, and snippets.

@swiety85
Last active June 2, 2021 15:51
Show Gist options
  • Save swiety85/334b50856ad8463e74922acff18fdcb9 to your computer and use it in GitHub Desktop.
Save swiety85/334b50856ad8463e74922acff18fdcb9 to your computer and use it in GitHub Desktop.
React Native HOC (Higher Order Component) that adds 'orientation' and 'isLandscape' props to the component
import React, { useState, useEffect } from 'react';
import { Dimensions } from 'react-native';
const getOrientation = () => Dimensions.get('window').width < Dimensions.get('window').height ? 'portrait' : 'landscape';
export default function withOrientation(WrappedComponent) {
return function (props) {
const [orientation, setOrientation] = useState(getOrientation());
useEffect(() => {
Dimensions.addEventListener('change', () => setOrientation(getOrientation()));
return () => Dimensions.removeEventListener('change');
}, [])
return <WrappedComponent {...props} orientation={orientation} isLandscape={orientation === 'landscape'} />;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment