Methods

  • Use arrow functions to close over local variables.

    1. function ItemList(props) {
    2. return (
    3. <ul>
    4. {props.items.map((item, index) => (
    5. <Item
    6. key={item.key}
    7. onClick={() => doSomethingWith(item.name, index)}
    8. />
    9. ))}
    10. </ul>
    11. );
    12. }
  • Bind event handlers for the render method in the constructor. eslint: react/jsx-no-bind

    Why? A bind call in the render path creates a brand new function on every single render.

    1. // bad
    2. class extends React.Component {
    3. onClickDiv() {
    4. // do stuff
    5. }
    6. render() {
    7. return <div onClick={this.onClickDiv.bind(this)} />;
    8. }
    9. }
    10. // good
    11. class extends React.Component {
    12. constructor(props) {
    13. super(props);
    14. this.onClickDiv = this.onClickDiv.bind(this);
    15. }
    16. onClickDiv() {
    17. // do stuff
    18. }
    19. render() {
    20. return <div onClick={this.onClickDiv} />;
    21. }
    22. }
  • Do not use underscore prefix for internal methods of a React component.

    Why? Underscore prefixes are sometimes used as a convention in other languages to denote privacy. But, unlike those languages, there is no native support for privacy in JavaScript, everything is public. Regardless of your intentions, adding underscore prefixes to your properties does not actually make them private, and any property (underscore-prefixed or not) should be treated as being public. See issues #1024, and #490 for a more in-depth discussion.

    1. // bad
    2. React.createClass({
    3. _onClickSubmit() {
    4. // do stuff
    5. },
    6. // other stuff
    7. });
    8. // good
    9. class extends React.Component {
    10. onClickSubmit() {
    11. // do stuff
    12. }
    13. // other stuff
    14. }
  • Be sure to return a value in your render methods. eslint: react/require-render-return

    1. // bad
    2. render() {
    3. (<div />);
    4. }
    5. // good
    6. render() {
    7. return (<div />);
    8. }