React: Is setting the defaultProps correct in this way?

Created on 13 Dec 2018  Â·  3Comments  Â·  Source: facebook/react

export default class extends PureComponent {
...
  render() {
    const { size = 24, content, mode, color = 'rgb(97, 144, 232)', height = '160px' } = this.props
    return (
      <div className="loading" style={{ minHeight: height, height }}>
        <div className="inner">
          <div className="icon" style={{ width: `${size}px`, height: `${size}px` }}>
            <Iconfont size={size} color={color} type="loading" />
          </div>
          {content && <div className="content">{content}</div>}
        </div>
      </div>
    )
  }
}

Set the defaultProps with ES6 destructuring. If the way is incorrect, why? Does it has any side effect?

Most helpful comment

export default class extends PureComponent {
  static defaultProps = {
    size: 24,
    color: 'rgb(97, 144, 232)',
    height: '160px',
  }

  ...

  render() {
    const { size, content, mode, color, height } = this.props
    return (
      <div className="loading" style={{ minHeight: height, height }}>
        <div className="inner">
          <div className="icon" style={{ width: `${size}px`, height: `${size}px` }}>
            <Iconfont size={size} color={color} type="loading" />
          </div>
          {content && <div className="content">{content}</div>}
        </div>
      </div>
    )
  }
}

All 3 comments

export default class extends PureComponent {
  static defaultProps = {
    size: 24,
    color: 'rgb(97, 144, 232)',
    height: '160px',
  }

  ...

  render() {
    const { size, content, mode, color, height } = this.props
    return (
      <div className="loading" style={{ minHeight: height, height }}>
        <div className="inner">
          <div className="icon" style={{ width: `${size}px`, height: `${size}px` }}>
            <Iconfont size={size} color={color} type="loading" />
          </div>
          {content && <div className="content">{content}</div>}
        </div>
      </div>
    )
  }
}

That's ok, but defaultProps is preferred because it transforms your this.props.

In your case, you won't have your "default" values when you access this.props elsewhere. It's a rather minor difference.

However this is a better option for function components. defaultProps was introduced specifically to solve classes problem.

Was this page helpful?
0 / 5 - 0 ratings