Charles Brown
Charles Brown

Reputation: 927

Combine 2 render into 1 render in React

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

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53894

Try deciding the render on componentDidMount because the DOM references are available at this point.

See "React updates ­D­O­M and refs" component lifecycle diagram.

enter image description here

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

Related Questions