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
A basic functional component looks like:
You can’t use hooks in class based Components.
try:
Hey you can use this in your class based components to get the window
height
andwidth
Check this
Hope it helps, feel free for doubts