'How to sync both parent and child height of onLayout of View when dynamic content is increasing in between components
Do you know that how to sync both parent and child height of onLayout of View when dynamic content is increasing in between components?
For this question, I can give you correct answer below:
First of all, This is parent class component codes.
export default class ViewLayoutParent extends Component<any, any> {
constructor(props: any) {
super(props);
this.state = {
layoutViewHeight: 0,
list: [],
}
}
componentDidMount() {
this.setState({
list: this.initListData(),
});
}
initListData = () => {
return [
{
id: '100001',
name: 'Victor.Xue',
age: 29,
}, {
id: '100002',
name: 'Austin Snow',
age: 29,
}
];
}
onAddItemToList = () => {
const oldList = this.state.list;
const newItem = {
id: '10000'.concat((oldList.length + 1).toString()),
name: 'Victor.Xue'.concat((oldList.length + 1).toString()),
age: 29 + oldList.length + 1,
};
let newList: any = oldList;
newList.push(newItem);
this.setState(
{
list: newList,
}
);
}
onLayoutFun = (event: any) => {
const { height } = event.nativeEvent.layout;
console.log('Parent height height is ::: ' + height);
this.setState({
layoutViewHeight: height,
});
}
render() {
return (
this.state.list.length === 0 ? null :
<ScrollView scrollEnabled={true}>
<View style={styles.container} onLayout={(event: any) => this.onLayoutFun(event)}>
{this.state.list.map((item: any) => {
return (
<View style={styles.container} key={item?.id}>
<Text style={styles.nameText}>{item?.name}</Text>
</View>
)
})}
</View>
<ViewLayoutChild layoutViewHeight={this.state.layoutViewHeight}></ViewLayoutChild>
<Button title="Add Item" color={'red'} onPress={this.onAddItemToList}></Button>
</ScrollView>
)
}
}
Here is child class component codes:
export default class ViewLayoutChild extends Component<viewLayoutChildProps, any> {
constructor(props: viewLayoutChildProps) {
super(props);
}
UNSAFE_componentWillReceiveProps(nextProps: any) {
console.log('Child height is ::: ' + nextProps.layoutViewHeight);
}
render(): React.ReactNode {
return null;
};
}
We can using UNSAFE_componentWillReceiveProps of method of react to getting nextProps.layoutViewHeight value when height of onLayout of View is changed
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
