Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React defaultProps not working

I'm probably doing something stupid, but I can't get defaultProps to work.

export default class MyClass extends Component{
  static propTypes = {
    name: React.PropTypes.string.isRequired,
    field: React.PropTypes.object.isRequired
  }

  static defaultProps = {
    field: { value: '', errors: [] }
  }

  render() {
    // blah blah
  }
}

I have code that relies on this.props.field.value and this.props.field.errors.length and all my tests are blowing up with TypeError: 'undefined' is not an object (evaluating 'this.props.field.errors.length'), shouldn't my default props give it a default value? Initially, my field prop is an empty object.

like image 438
Lee Avatar asked Oct 21 '15 14:10

Lee


1 Answers

Initially, my field prop is an empty object.

Default props are only used if no value is passed for the prop. It is is shallow merge, not a deep merge.

From the docs (emphasis mine):

The result of getDefaultProps() will be cached and used to ensure that this.props.value will have a value if it was not specified by the parent component.

like image 163
Felix Kling Avatar answered Oct 21 '22 06:10

Felix Kling