Linter · Rules
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
Reported:
class Button extends React.Component {
static get defaultProps() {
return { label: "OK" };
}
render() {
return <button>{this.props.label}</button>;
}
}
Button.propTypes = {
label: PropTypes.string,
};
Not reported:
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:
class Button extends React.Component {
static propTypes = {
label: PropTypes.string,
};
}
With "static getter", this isn't reported:
class 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:
class Button extends React.Component {
static defaultProps = {
label: "OK",
};
}
Button.propTypes = {
label: PropTypes.string,
};