getDefaultProps method inside of class, versus class.DefaultProps

I have a react component called SkiDaysCount, where I output some data and make a simple calculation.

What is the difference between declaring the default props with the getDefaultProps method like such

getDefaultProps() {
  return {
    total: 50,
    powder: 50,
    backcountry: 15,
    goal: 75
  };
}

and assigning them in your App.js/Index.js like this:

SkiDaysCount.defaultProps = {
  total: 50,
  powder: 10,
  BackCountry: 15,
  goal: 75
};

and then just assigning the values inside the place, where you place your component

<SkiDaysCount
  total={70}
  powder={20}
  backcountry={10}
  goal={75}
/>

Upvotes: 2

Views: 427

Answers (1)

Tholle
Tholle

Reputation: 112807

Using the getDefaultProps method used to be the way to set default props with createReactClass. This way of setting default props doesn't work with ES6 classes, so you need to use defaultProps for that.

Example

class SkiDaysCount1 extends React.Component {
  getDefaultProps() {
    return {
      total: 50,
      powder: 50,
      backcountry: 15,
      goal: 75
    };
  }

  render() {
    return <div>{JSON.stringify(this.props)}</div>;
  }
}

class SkiDaysCount2 extends React.Component {
  static defaultProps = {
    total: 50,
    powder: 50,
    backcountry: 15,
    goal: 75
  };

  render() {
    return <div>{JSON.stringify(this.props)}</div>;
  }
}

ReactDOM.render(
  <div>
    <SkiDaysCount1 />
    <SkiDaysCount2 />
  </div>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Upvotes: 2

Related Questions