How can I listen on Dimension.get('window').height
within a component so when user rotate the device or the web user resize the browser window then my layout can reflow?
I have checked existing HoC, but haven't found one, a lib would also be an accepted answer.
The React Native docs mention a addEventListener
on the Dimensions
API. You just need to pass it a function and whenever this is triggered, use setState
to update whatever values you need.
You could use it like this:
import React, { Component } from 'react';
import { Dimensions } from 'react-native';
class DimensionsWrapper extends Component {
state = {
landscape : Dimensions.get('window').height < Dimensions.get('window').width
}
componentDidMount() {
Dimensions.addEventListener('change', this._onDimensionsChange);
}
componentWillUnmount() {
Dimensions.removeEventListener('change', this._onDimensionsChange);
}
_onDimensionsChange(event) {
const { width, height } = event.window;
const landscape = height < width;
this.setState({ landscape });
}
...
}