ffxsam ffxsam - 1 month ago 4
React JSX Question

Is it OK to put propTypes and defaultProps as static props inside React class?

This is the way I've been doing it for quite some time now:

export default class AttachmentCreator extends Component {
render() {
return <div>
<RaisedButton primary label="Add Attachment" />
</div>
}
}

AttachmentCreator.propTypes = {
id: PropTypes.string,
};


But I've seen people doing it this way:

export default class AttachmentCreator extends Component {
static propTypes = {
id: PropTypes.string,
};

render() {
return <div>
<RaisedButton primary label="Add Attachment" />
</div>
}
}


And in fact I've seen people setting initial state outside the constructor as well. Is this good practice? It's been bugging me, but I remember a discussion somewhere where someone said that setting default props as a static is not a good idea - I just don't remember why.

Answer

non-function properties are not currently supported for es2015 classes. its a proposal for es2016. the second method is considerably more convenient, but a plugin would be required to support the syntax (theres a very common babel plugin for it).

On the other end, a hand full of open source projects are beginning to treat proptypes like TypeScript interfaces, or ActionConstants and actually create separate folders/files that house various component prop types and are then imported into the component.

So in summary, both syntaxes are ok to use. but if you want to only use strictly ES2015, the latter syntax is not yet supported in the specification.