Reputation: 927
I have two components in the render function.
If the second component has height higher than the first component, hide the second component
Below is the snippet I wrote:
isOverflow = () => {
const { component1, component2 } = this;
if (component2.clientHeight > component1.clientHeight) {
this.setState({ isOverflow: true });
} else {
this.setState({ isOverflow: false });
}
}
See my snippet in my render function.
<div ref={ref => (this.component1 = ref)}</div>
<div ref={ref => (this.component2 = ref)} style={{ visibility: !isOverflow ? 'visible' : 'hidden' }}>
And I face a problem here, in React I need to render at least 1 time to get the height, and I need another render to hide the component.
This implementation looks ugly because it is like showing an animation (2 renders)
Can I achieve both in 1 render only?
[Note: The height is a dynamic value. Therefore, I cannot achieve this by CSS. I must use Javascript here.]
Upvotes: 0
Views: 171
Reputation: 53894
Try deciding the render on componentDidMount
because the DOM references are available at this point.
See "React updates DOM and refs" component lifecycle diagram.
componentDidMount = () => {
this.setState({ hide: this.component2.clientHeight > this.component1.clientHeight });
};
<>
<div ref={(ref) => (this.component1 = ref)} />
<div
ref={(ref) => (this.component2 = ref)}
style={{ visibility: this.state.hide ? "hidden" : "visible" }}
/>
</>
Upvotes: 1