Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of getDefaultProps function using ES6 in React Native?

Tags:

react-native

I was looking at the documentation for the DatePickerIOS component and they use getDefaultProps() to initialize the props in the component.

  getDefaultProps: function () {
    return {
      date: new Date(),
      timeZoneOffsetInHours: (-1) * (new Date()).getTimezoneOffset() / 60,
    };
  },

  getInitialState: function() {
    return {
      date: this.props.date,
      timeZoneOffsetInHours: this.props.timeZoneOffsetInHours,
    };
  },

What is the equivalent of that using ES6 syntax? Because I have been using:

constructor(props) {
  super(props);

  this.state = {
    //equivalent to getInitialState is here
  };
}

should I do this.props = { } to set up my default props?

like image 839
nbkhope Avatar asked Aug 23 '16 21:08

nbkhope


Video Answer


2 Answers

See this:

https://github.com/facebook/react/issues/3725

class X extends React.Component {
}
X.defaultProps = {...}

If you are using the babel-plugin-transform-class-properties package, you can do this:

class X extends React.Component {
  static defaultProps = {...}
}
like image 86
Josh Rieken Avatar answered Nov 19 '22 12:11

Josh Rieken


class Video extends React.Component {
  static defaultProps = {
    autoPlay: false,
    maxLoops: 10,
  }
  static propTypes = {
    autoPlay: React.PropTypes.bool.isRequired,
    maxLoops: React.PropTypes.number.isRequired,
    posterFrameSrc: React.PropTypes.string.isRequired,
    videoSrc: React.PropTypes.string.isRequired,
  }
  state = {
    loopsRemaining: this.props.maxLoops,
  }
}

https://babeljs.io/blog/2015/06/07/react-on-es6-plus

like image 27
stereodenis Avatar answered Nov 19 '22 10:11

stereodenis