React Props in React Default props

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

Example

defaultProps allows you to set default, or fallback, values for your component props. defaultProps are useful when you call components from different views with fixed props, but in some views you need to pass different value.

Syntax

ES5


var MyClass = React.createClass({
  getDefaultProps: function() {
    return {
      randomObject: {},
      ...
    };
  }
}

ES6


class MyClass extends React.Component {...}
  
MyClass.defaultProps = {
    randomObject: {},
    ...
}

ES7


class MyClass extends React.Component {  
    static defaultProps = {
        randomObject: {},
        ...
    };
}

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



Got any React Question?