skip to Main Content

I am working on React Native app for which I have all the components are class based. Now I have to implement the screen rotation functionality that change the design according to screen rotation. I am trying to use the library useWindowDimensions from react native, but it throws error that hooks can’t be called from non functional component.

Can anyone tell how to use hooks in class based component, or any other approach to detect the screen dimension to make screen responsive for screen rotation?

Update: I used the event listener to get the screen orientation, but the problem is the global variable are not updating in the stylesheets, but it is working in inline styling. Here is the minimum viable example code:

   import {Dimensions} from 'react-native';

    var screenWidth = Dimensions.get('window').width
    var screenHeight = Dimensions.get('window').height
    
        class ABC extends Comp {
        
        componentDidMount() {
        Dimensions.addEventListener("change", (handler) => 
        this.forceUpdate();
        width = handler.window.width;
        }
        render(){
        
        return(
        // If I directly access width here, I get updated value, but if I use stylesheet, I am getting old value
        )
        }
        
        }

const styles = StyleSheet.create({
container:{
width: screenwidth
}
}) 

3

Answers


  1. A basic functional component looks like:

    const MyComponent = () => {
        const { height, width } = useWindowDimensions();
        return <>height: {height}, width: {width}</>;
    }
    

    You can’t use hooks in class based Components.

    Login or Signup to reply.
  2. try:

    import { Dimensions } from 'react-native';
    // in your class component
    componentDidMount() {
        Dimensions.addEventListener("change", (handler) => this.setState({
        wHeight: handler.window.height,
        wWidth: handler.window.width
        })
    }
    
    Login or Signup to reply.
  3. Hey you can use this in your class based components to get the window height and width

    Check this

        import {Dimensions} from 'react-native';
    
    const screenWidth = Dimensions.get('window').width
        const screenHeight = Dimensions.get('window').height
        
            class ABC extends Comp {
            
            
            render(){
            const screenWidth = Dimensions.get('window').width
            const screenHeight = Dimensions.get('window').height
            return(
            )
            }
            
            }
    
    const styles = StyleSheet.create({
    main:{
    padding:screenWidth==25?20:30
    }
    })
    

    Hope it helps, feel free for doubts

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search