react-native: getDefaultProps doesn't work with ES6 syntax; warning is not helpful
I’m trying to build a component that defines a default value for a required prop, but it doesn’t seem to work.
class ReviewsList extends Component {
propTypes: {
reviews : React.PropTypes.array.isRequired,
}
getDefaultProps() {
return {
reviews: [],
};
}
render() {
var reviewItems = this.props.reviews.map(function (review) { // ERROR
return (
<RecipeReviewItem key={review.objectId} reviewText={review.reviewText}></RecipeReviewItem>
)
});
return (
<View>{reviewItems}</View>
);
}
}
When I run this, I get:
ERROR: undefined is not an object (evaluating 'this.props.reviews.map')
Why?
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Comments: 20 (2 by maintainers)
For future visitors, ES6 syntax for latest version should be ( none of the above ):
Revised
for future users here is es2015 syntax for defaultprops…
defaultProps
just needs to be a static property on the component class. How you want to do this is up to you.Static property:
Static getter:
Assign a property:
should work
try this
found solution from http://www.newmediacampaigns.com/blog/refactoring-react-components-to-es6-classes
Original
New
static get defaultProps() { return { yourkey: yourvalue } }
Upon inspecting the console log I got this message:
What does that even mean? What’s a static property? How do you ‘define
defaultProps
’? An example is worth its weight in gold here.I’ve just learned that ES6 has the
static
keyword, but seriously, what’s a static property?works like charm with es6
@AlexChaseJones your suggestion works like a charm.
People on facebook could update their official docs at http://facebook.github.io/react-native/docs/using-navigators.html
Thanks @cyprusglobe. Fantastic answer, and a really informative link. It’s working very well now, thanks. When RN moves towards ES6 in earnest the documentation examples must be updated to show this.
It’s at Stage 2 and the champion is currently at Facebook. I think the syntax might change (or might not) but you could write a codemod or similar source transformer to transpile from old syntax to new if that happened.
isRequired doesn’t throw an error when the prop isn’t provided… I’ve had this issue with RN ES6 for a long time. Am I missing something?
I’ve tried
and
But neither of these have worked.