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:

bunfig.toml
[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.

bunfig.toml
[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#

example.jsx2 problems
class Button extends React.Component {
  static get defaultProps() {
    return { label: "OK" };
  }

  render() {
    return <button>{this.props.label}</button>;
  }
}

Button.propTypes = {
  label: PropTypes.string,
};
example.jsxNo problems
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:

example.jsxNo problems
function Button({ label }) {
  return <button>{label}</button>;
}

Button.propTypes = {
  label: PropTypes.string,
};

Options#

bunfig.toml
[lint.rules]
"react/static-property-placement" = ["error", "property assignment"]
OptionWhat 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:

example.jsxwith "property assignment"1 problem
class Button extends React.Component {
  static propTypes = {
    label: PropTypes.string,
  };
}

With "static getter", this isn't reported:

example.jsxwith "static getter"No problems
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:

example.jsxwith "static public field", { "propTypes": "property assignment" }No problems
class Button extends React.Component {
  static defaultProps = {
    label: "OK",
  };
}

Button.propTypes = {
  label: PropTypes.string,
};