Home > Back-end >  How to use React Hooks inside Class Component "useWindowDimensions"
How to use React Hooks inside Class Component "useWindowDimensions"

Time:09-06

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?

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related