Skip to content

Commit

Permalink
listenOrientationChange to support hooks
Browse files Browse the repository at this point in the history
Encapsulate the changes inspired by marudy#70
  • Loading branch information
gregfenton authored Aug 7, 2020
1 parent 718722b commit 996b66e
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,24 +38,37 @@ const heightPercentageToDP = heightPercent => {
};

/**
* Event listener function that detects orientation change (every time it occurs) and triggers
* Event listener function that detects orientation change (every time it occurs) and triggers
* screen rerendering. It does that, by changing the state of the screen where the function is
* called. State changing occurs for a new state variable with the name 'orientation' that will
* always hold the current value of the orientation after the 1st orientation change.
* Invoke it inside the screen's constructor or in componentDidMount lifecycle method.
* @param {object} that Screen's class component this variable. The function needs it to
* invoke setState method and trigger screen rerender (this.setState()).
* @param {object} classComponent This Screen's class component this variable.
* listenOrientationChange() needs it to invoke the class's setState
* (this.setState()) method and trigger screen rerender.
* @param {object} setStateHook A set-state function, typically from useState().
* listenOrientationChange() calls it to set the state value and
* trigger screen rerender.
* @throws {Error} If neither or both of the params are set. Must only set ONE of them.
*/
const listenOrientationChange = that => {
const listenOrientationChange = ({classComponentThis = null, setStateHook = null}) => {
Dimensions.addEventListener('change', newDimensions => {
// Retrieve and save new dimensions
screenWidth = newDimensions.window.width;
screenHeight = newDimensions.window.height;

// Trigger screen's rerender with a state update of the orientation variable
that.setState({
let orientation = {
orientation: screenWidth < screenHeight ? 'portrait' : 'landscape'
});
};

// Trigger screen's rerender with a state update of the orientation variable
if (classComponentThis && ! setStateHook) {
classComponentThis.setState(orientation);
} else if (setStateHook && !classComponentThis) {
setStateHook(orientation);
} else {
throw new Error("Must set only ONE of classComponentThis or setStateHook");
}
});
};

Expand Down

0 comments on commit 996b66e

Please sign in to comment.