I cannot understand how can I send parent view's sizes to child component of this. In renderPager() I want calculate some parameters that depend on parent view size. I know that we can do it through onLayout(). problem is that onLayout will be called only after building all of childs (I see it by the console log). how can I do it?
onPageLayout = (event) => {
const { width, height } = event.nativeEvent.layout;
console.log("ON LAYOUT");
};
render() {
return (
<View
style={styles.root}
onLayout={this.onPageLayout}
>
{this.renderPager()}
</View>
);
}
renderPager = () => {
// how can get root view's size here
return (
<IndicatorViewPager
ref={(ref) => (this.viewPager = ref)}
scrollEnabled={!this.state.isDragging}
onPageScroll={this.onPageScroll}
style={styles.pageRoot}
>
{this.renderPages()}
</IndicatorViewPager>
);
};
thank you
To get the parent height and width in React: Set the ref prop on the element. In the useEffect hook, update the state variables for the height and width. Use the offsetHeight and offsetWidth properties to get the height and width of the element.
import { Dimensions } from 'react-native'; You can get the application window's width and height using the following code: const windowWidth = Dimensions. get('window').
The general way to set the dimensions of a component is by adding a fixed width and height to style. All dimensions in React Native are unitless, and represent density-independent pixels.
You can maybe pass the data as props, and take the prop data from the store. You are right in that onLayout
will only be triggered after everything is rendered, but that simply means that you have to pass the props with a null value on the first render. For instance:
onPageLayout = (event) => {
const { width, height } = event.nativeEvent.layout;
console.log("ON LAYOUT");
this.setState({width, height})
};
render() {
return (
<View
style={styles.root}
onLayout={this.onPageLayout}
>
{this.renderPager(this.state.width, this.state.height)}
</View>
);
}
renderPager = (width, height) => {
// Do something if width or height are null
// how can get root view's size here
return (
<IndicatorViewPager
ref={(ref) => (this.viewPager = ref)}
scrollEnabled={!this.state.isDragging}
onPageScroll={this.onPageScroll}
style={styles.pageRoot}
>
{this.renderPages()}
</IndicatorViewPager>
);
};
Also you could use the measure
function of the parent, but I think that might be a bit cumbersome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With