How to conditionally set default props


(Mohsin Ul Haq) #1

I have a tooltip component that takes trigger prop as ‘click’ or ‘hover’ and a delay prop as time in ms.
I want to set the default value of delay prop based on the value of trigger prop. But I am unable to do that as follows:

static defaultProps = {
    delay: this.props.trigger === 'hover' ? 100: 0
};

But we can’t access this inside static fields. How can I best do this task?


(James K Nelson) #2

The way I’d do this would be to create a getDelay() method, and use that instead of accessing this.props.delay directly.

For example:

getDelay() {
  if (this.props.delay !== undefined) {
    return this.props.delay
  }
  else {
    return this.props.trigger === 'hover' ? 100: 0
  }
}

If you don’t like the idea of calling a function every time, you could also create a getter instead:

get delay() {
  // same as above
}

And then access it through this.delay.