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
4
Answers
You can use hooks only inside react components. Since
useDimensions
is a hook you can only use it like this:Other than the fact hooks must be called inside a function use should remove the eventlistener inside the useEffect.
Use can get height and width simply by window.innerHeight and window.innerWidth. By this two you can get height and width of windows.
You can update your function like this:
And you can use it by importing: