0

Let's say I've got a Tooltip component that shows & hides depending on whether there is text data for it or not:

{this.state.tooltipText && (
  <Tooltip
    text={this.state.tooltipText} />
)}

If I wanted to transition this component in and out, I might instead include a boolean on prop and let the component manage transitioning out itself.

<Tooltip
  on={this.state.tooltipText !== null}
  text={this.state.tooltipText} />

With this setup, though, I lose the text prop right when the transition out should begin. There is very clearly never a state where on is false and I still have access to the text prop.

Is there a good way to handle this scenario?

  • Should the component keep an internal record of the previous state of tooltipText?
  • Or is it best to use two properties to track the state of the tooltip (tooltipOn and tooltipText) and never erase this.state.tooltipText?
Scott Thiessen
  • 873
  • 7
  • 20

1 Answers1

1

Should the component keep an internal record of the previous state of tooltipText?

Yes. Otherwise the parent would have to decide when the transition starts / ends, which is not his authority.

Actually componentWillReceiveProps is best for this as you can access the current & next props:

 componentWillReceiveProps(nextProps) {
  if(this.props.text && !nextProps.text) {
    this.fadeOut();
  } else if(!this.props.text && nextProps.text) {
    this.setState({ text: nextProps.text });
    this.fadeIn();
  }
}

Then the parent just has:

 <Tooltip text={this.state.tooltipText} />
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 2
    `componentWllReceiveProps` is being deprecated in React 17: https://stackoverflow.com/questions/51980977/why-is-componentwillreceiveprops-deprecated – Evan Trimboli Oct 08 '18 at 22:42
  • Looks like this is actually not the right way to go. As @EvanTrimboli points out, `componentWillReceiveProps` is being deprecated. Also, this solution creates a duplicate, separate `text` state for the component. – Scott Thiessen Oct 11 '18 at 19:35
  • I opted to go w/ the `tooltipOn` + `toolTipText` option, and it's working well enough – Scott Thiessen Oct 11 '18 at 19:37
  • @SCCOTT well `getDerivedStateFromProps` would also work, and thats not deprecated. "looks like this is actually not the right way to go", thats how I'd do it, I haven't said that this is the best solution ... – Jonas Wilms Oct 12 '18 at 10:58