DevPy
DevPy

Reputation: 497

How to use React Hooks inside Class Component "useWindowDimensions"

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
}
}) 

Upvotes: 0

Views: 1318

Answers (3)

Gaurav Roy
Gaurav Roy

Reputation: 12235

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

Upvotes: 0

Yoav Karpassi
Yoav Karpassi

Reputation: 31

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
    })
}

Upvotes: 1

Halcyon
Halcyon

Reputation: 57721

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.

Upvotes: 2

Related Questions