Anyone have any simple example on what parameter to pass to
ScreenOrientation.addOrientationChangeListener()
After looking at the docs here and playing around with it, I still can’t understand how to use it.
The docs say
listener (OrientationChangeListener)
Each orientation update will pass an object with the new OrientationChangeEvent to the listener.
And there is a link to a change event here
This is what my code looks like:
const orientationListener = async () => {
ScreenOrientation.addOrientationChangeListener(
ScreenOrientation.ScreenOrientationInfo.orientation
);
};
but I am getting a type error in VSCode. That’s where I am stuck. What argument to pass to ScreenOrientation.addOrientationChangeListener()
? I am getting an error
property 'orientationchangelistener' does not exist on type 'typeof import' (path to node_modules folder where ScreenOrientation package is installed) ts
which doesn’t make sense since I have this at the top of the file:
import * as ScreenOrientation from "expo-screen-orientation";
Hey @dj-designs , as the docs say- it accepts a listener, which you can think of as just a function basically. This listener is triggered whenever a change in orientation occurs. For instance:
ScreenOrientation.addOrientationChangeListener( (event) => {
console.log("orientation changed");
}
);
will log that message whenever the orientation changes.
Thank you for the information. Makes sense. Sounds like I can update state in the event function.
My goal is to make slight modification to css based on landscape orientation.
Custom Hook
import { useState, useEffect } from "react";
import {
Orientation,
getOrientationAsync,
addOrientationChangeListener,
} from "expo-screen-orientation";
export default function useOrientation() {
const [orientation, setOrientation] = useState<Orientation>(0);
useEffect(() => {
getOrientationAsync().then((value) => {
setOrientation(value);
});
const subscription = addOrientationChangeListener((event) => {
setOrientation(event.orientationInfo.orientation);
});
return () => {
subscription.remove;
};
}, []);
return orientation;
}
// Usage
const orientation = useOrientation();
2 Likes
looks interesting!
I’ve never seen this syntax. What is meant by <
and >
?
Thank you.
Typescript type/enum
export declare enum Orientation {
UNKNOWN = 0,
PORTRAIT_UP = 1,
PORTRAIT_DOWN = 2,
LANDSCAPE_LEFT = 3,
LANDSCAPE_RIGHT = 4
}
Just ignore it if you are not using typescript.
1 Like
msaad
May 20, 2021, 8:40pm
7
Hi @charliecruzan .
I am having trouble with this on Android. I’m using sdk 39 at the moment, but android doesn’t catch the event
system
Closed
September 30, 2021, 5:54pm
8
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.