react/static-property-placement
Enforce where a class component declares propTypes, defaultProps and other static properties
A class component can declare propTypes in three ways: as a static field, as a static get accessor, or by assigning to the class after its body. All three work. In a codebase that mixes them, you have to look in several places to find a component's props.
The rule checks propTypes, defaultProps, childContextTypes, contextTypes, contextType and displayName. By default it asks for a static field. It ignores function components.
Configure#
Off by default. To turn it on:
[lint.rules]
"react/static-property-placement" = "error" # or "warn"Every option, set to its default. The ones that are commented out are unset by default.
[lint.rules]
"react/static-property-placement" = [
"error",
# "static public field", "static getter" or "property assignment"
"static public field",
{
# propTypes = <string>,
# defaultProps = <string>,
# childContextTypes = <string>,
# contextTypes = <string>,
# contextType = <string>,
# displayName = <string>,
},
]Examples#
class Button extends React.Component {
static get defaultProps() {defaultProps should be declared as a static class property.
return { label: "OK" };
}
render() {
return <button>{this.props.label}</button>;
}
}
Button.propTypespropTypes should be declared as a static class property. = {
label: PropTypes.string,
};class Button extends React.Component {
static propTypes = {
label: PropTypes.string,
};
static defaultProps = {
label: "OK",
};
render() {
return <button>{this.props.label}</button>;
}
}Function components aren't checked:
function Button({ label }) {
return <button>{label}</button>;
}
Button.propTypes = {
label: PropTypes.string,
};Options#
[lint.rules]
"react/static-property-placement" = ["error", "property assignment"]| Option | What it does |
|---|---|
"static public field" (default) | Require static propTypes = { ... } in the class body. |
"static getter" | Require static get propTypes() { ... } in the class body. |
"property assignment" | Require Button.propTypes = { ... } after the class. |
With "property assignment", this is reported:
"property assignment"1 problemclass Button extends React.Component {
static propTypes = {propTypes should be declared outside the class body.
label: PropTypes.string,
};
}With "static getter", this isn't reported:
"static getter"No problemsclass Button extends React.Component {
static get propTypes() {
return { label: PropTypes.string };
}
}A second option overrides the placement for individual properties. The keys are the six property names above:
"static public field", { "propTypes": "property assignment" }No problemsclass Button extends React.Component {
static defaultProps = {
label: "OK",
};
}
Button.propTypes = {
label: PropTypes.string,
};