I have a function for detecting the window width and height on changing the layout.
The function for detecting width and height work fine but the problem is using them on stylesheet file.
The error is: Invalid hook call. Hooks can only be called inside the body of a function component.
My Function:
import { useEffect, useCallback, useState } from 'react';
import { Dimensions } from 'react-native';
export function useDimensions () {
const [windowWidth, setWindowWidth] = useState(Dimensions.get('window').width);
const [windowHeight, setWindowHeight] = useState(Dimensions.get('window').height);
useEffect(() => {
const callback = () => {
setWindowWidth(Dimensions.get('window').width);
setWindowHeight(Dimensions.get('window').height);
}
Dimensions.addEventListener('change', callback);
}, []);
return {windowWidth, windowHeight};
};
Here is what I have tried in stylesheet (custom global stylesheet file) :
import { StyleSheet } from "react-native";
import Colors from "./Colors";
import { windowHeight, windowWidth } from '../App/Components/Dimensions';
import { useDimensions } from '../App/Components/TestDimesions';
// Here is the problem : Invalid hook call...
const orientation = useDimensions();
const Global = StyleSheet.create({
test:{
width: windowWidht
}
});
export default Global
CodePudding user response:
You can use hooks only inside react components. Since useDimensions
is a hook you can only use it like this:
function MyComponent() {
const orientation = useDimensions();
return (
<View style={[styles.test, { width: orientation.windowWidth }]} />
)
}
CodePudding user response:
Use can get height and width simply by window.innerHeight and window.innerWidth. By this two you can get height and width of windows.
CodePudding user response:
Other than the fact hooks must be called inside a function use should remove the eventlistener inside the useEffect.
useEffect(() => {
//here
const listener = Dimensions.addEventListener('change', callback);
return () => listener.remove();
}, []);