Component Methods And Properties
When creating React components it is more convenient to always follow the same organization for methods and properties order to easier find lifecycle methods, event handlers, static properties and render related elements:
- Static methods and properties: 1.1. Instance variables
- Lifecycle methods and properties:
2.1.
displayName2.2.propTypes2.3.contextTypes2.7.childContextTypes2.5.statics2.6.defaultProps2.7. Optionalstaticmethods 2.8.constructor(classes) 2.9.getDefaultProps2.10.getInitialState2.11.state2.12.getChildContext2.13.componentWillMount2.14.componentDidMount2.15.componentWillReceiveProps2.16.shouldComponentUpdate2.17.componentWillUpdate2.18.componentDidUpdate2.19.componentWillUnmount - Custom and instance methods:
3.1. Click and Event Handlers like e.g.
onClickSubmit()oronChangeValue()3.2. Getter and Setter methods forrenderlike e.g.getSelectReason()orgetFooterContent()3.3. Any custom method like e.g.calculateSnowflakes()3.4. Optionalrendermethods likerenderSnowflakes()orrenderWinterForest() render
ESLint: react/sort-comp
Examples
⇣ Incorrect code for this rule:
import React, { Component } from "react";
import PropTypes from "prop-types";
const propTypes = {
density: PropTypes.number.isRequired,
season: PropTypes.string
};
class Snow extends React.Component {
constructor() {
super();
this.state = {
// ...
};
}
componentWillReceiveProps() {
// ...
}
componentDidMount() {
// ...
}
renderSnowflakes() {
// ...
}
calculateDensity() {
// ...
}
onChangeSeason() {
// ...
}
static isFalling() {
return true;
}
static defaultProps = {
season: "Winter"
};
render() {
return <div onClick={this.onChangeSeason.bind(this)}>{this.props.season}</div>;
}
}
Snow.propTypes = propTypes;
export default Snow;
⇡ Correct code for this rule:
import React, { Component } from "react";
import PropTypes from "prop-types";
export default class Snow extends React.Component {
static propTypes = {
density: PropTypes.number.isRequired,
season: PropTypes.string
};
static defaultProps = {
season: "Winter"
};
static isFalling() {
return true;
}
constructor() {
super();
this.state = {
// ...
};
}
componentDidMount() {
// ...
}
componentWillReceiveProps() {
// ...
}
onChangeSeason = () => {
// ...
};
calculateDensity = () => {
// ...
};
renderSnowflakes = () => {
// ...
};
render() {
return <div onClick={this.onChangeSeason}>{this.props.season}</div>;
}
}