skip to Main Content

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


  1. 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 }]} />
      )
    }
    
    Login or Signup to reply.
  2. 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();
    }, []);
    
    Login or Signup to reply.
  3. Use can get height and width simply by window.innerHeight and window.innerWidth. By this two you can get height and width of windows.

    Login or Signup to reply.
  4. You can update your function like this:

    import { Dimensions } from 'react-native';
    
    export const ScreenWidth = Dimensions.get('window').width;
    export const ScreenHeight = Dimensions.get('window').height;
    

    And you can use it by importing:

    import { StyleSheet } from "react-native";
    import Colors from "./Colors";
    import { ScreenWidth, ScreenHeight } from '../App/Components/TestDimesions';
    
    const Global = StyleSheet.create({
      test:{
        width: ScreenWidth,
      }
    });
    
    export default Global
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search