"Go" Airbnb React code specification

Source: Internet
Author: User
Tags closing tag es6 class


Airbnb's code specification is a very popular set of specifications in the industry, and it has been evolving to introduce the latest technology specifications
Original: https://zhuanlan.zhihu.com/p/20616464


Write react and JSX in a more reasonable way


Basic rules
    • Each file consists of only one react component;
      • However, a stateless or Pure component allows a file to contain multiple components. Eslint:react/no-multi-comp.
    • Always use JSX syntax;
    • Do not use the React.createelement method unless the file that initializes the app is not in the JSX format.
Class vs React.createclass vs Stateless

  • If the component has internal state or refs, it is more recommended to use class extends react.component unless you have a very good reason to use mixin. Eslint:react/prefer-es6-class



     
    
    // bad const Listing = React.createClass({
      // ...
      render() {
        return <div>{this.state.hello}</div>;
      }
    }); // good class Listing extends React.Component {
      // ...
      render() {
        return <div>{this.state.hello}</div>;
      }
    }





    If no component does not have an internal state or refs, then the normal function (do not use the arrow function) is better than the class:



    // bad
    Class Listing extends React.Component {
       Render() {
         Return <div>{this.props.hello}</div>;
       }
    }
    
    // bad (because the arrow function does not have a "name" attribute)
    Const Listing = ({ hello }) => (
       <div>{hello}</div>
    );
    
    // good
    Function Listing({ hello }) {
       Return <div>{hello}</div>;
    } 




Named
  • extension : React component uses the. jsx extension;
  • file Name: The file name is named with Pascal. For example: RESERVATIONCARD.JSX.
  • reference naming : The React component uses the Pascal name, the reference instance uses the hump to name. Eslint:react/jsx-pascal-case


    // bad
    import reservationCard from ‘./ReservationCard‘;
    
    // good
    import ReservationCard from ‘./ReservationCard‘;
    
    // bad
    const ReservationItem = <ReservationCard />;
    
    // good
    const reservationItem = <ReservationCard />;


  • component naming : The component name should be the same as the file name, for example: RESERVATIONCARD.JSX should have a Reservationcard reference name. However, if you are a component in a directory, you should use INDEX.JSX as the file name and use the folder name as the component name:


     
    
     
    
    // bad
    import Footer from ‘./Footer/Footer‘;
    
    // bad
    import Footer from ‘./Footer/index‘;
    
    // good
    import Footer from ‘./Footer‘;


Statement
    • Do not use the ' DisplayName ' property to name the component, you should use the reference name of the class.


       
      
       
      
      // bad
      export default React.createClass({
        displayName: ‘ReservationCard‘,
        // stuff goes here
      });
      
      // good
      export default class ReservationCard extends React.Component {
      }


Snap To
    • Use the following pairs of methods for the JSX syntax. Eslint:react/jsx-closing-bracket-location


       
      
      // bad
      <Foo superLongParam="bar"
           anotherSuperLongParam="baz" />
      
      // good
      <Foo
        superLongParam="bar"
        anotherSuperLongParam="baz"
      />


      // If the component's properties can be placed on the current row in one row
      <Foo bar="bar" />
      
      // multi-line attribute is indented
      <Foo
         superLongParam="bar"
         anotherSuperLongParam="baz"
      >
         <Quux />
      </Foo> 


Quotes
    • JSX attributes are quoted in double quotes, and the other JS uses single quotes. Eslint:jsx-quotes

      Why did you do that? The JSX property cannot contain escaped quotation marks, so it is more convenient to use double quotes when entering abbreviations such as "Don ' t".

      Standard HTML attributes also typically use double quotes, so the JSX property also adheres to this Convention.

      // bad
        <Foo bar=‘bar‘ />
      
        // good
        <Foo bar="bar" />
      
        // bad
        <Foo style={{ left: "20px" }} />
      
        // good
        <Foo style={{ left: ‘20px‘ }} />


Space
    • Start by adding a space before the self-closing tag.


       
      
       
      
      // bad
      <Foo/>
      
      // very bad
      <Foo                 />
      
      // bad
      <Foo
       />
      
      // good
      <Foo />


Property
  • The
  • Property name always uses the hump naming method.


    // bad
    <Foo
      UserName="hello"
      phone_number={12345678}
    />
    
    // good
    <Foo
      userName="hello"
      phoneNumber={12345678}
    />

     

  • When the property value equals True, the assignment of the property is omitted. Eslint:react/jsx-boolean-value


     
    
    // bad
    <Foo
      hidden={true}
    />
    
    // good
    <Foo
      hidden
    />


Brackets

  • Wrap multiple lines of JSX tags in parentheses. Eslint:react/wrap-multilines



     
    
     
    
    // bad
    render() {
      return <MyComponent className="long body" foo="bar">
               <MyChild />
             </MyComponent>;
    }
    
    // good
    render() {
      return (
        <MyComponent className="long body" foo="bar">
          <MyChild />
        </MyComponent>
      );
    }
    
    // good, when single line
    render() {
      const body = <div>hello</div>;
      return <MyComponent>{body}</MyComponent>;
    }




Label
    • The label is always self-closing when the label has no child elements. Eslint:react/self-closing-comp


       
      
      // bad
      <Foo className="stuff"></Foo>
      
      // good
      <Foo className="stuff" />


    • If the control has multiple lines of properties, close the label to another row. Eslint:react/jsx-closing-bracket-location


       
      
      // bad
      <Foo
        bar="bar"
        baz="baz" />
      
      // good
      <Foo
        bar="bar"
        baz="baz"
      />


Method

  • In the Render method, the callback function for the event should bind the bind in the constructor. Eslint:react/jsx-no-bind


    Why did you do that? The bind call in the Render method creates a completely new function each time a call to render occurs.

     
    
    // bad
      class extends React.Component {
        onClickDiv() {
          // do stuff
        }
    
        render() {
          return <div onClick={this.onClickDiv.bind(this)} />
        }
      }
    
      // good
      class extends React.Component {
        constructor(props) {
          super(props);
    
          this.onClickDiv = this.onClickDiv.bind(this);
        }
    
        onClickDiv() {
          // do stuff
        }
    
        render() {
          return <div onClick={this.onClickDiv} />
        }
      }




  • Do not use the underscore prefix for internal method naming of React components.


     
    
    // bad
    React.createClass({
      _onClickSubmit() {
        // do stuff
      },
    
      // other stuff
    });
    
    // good
    class extends React.Component {
      onClickSubmit() {
        // do stuff
      }
    
      // other stuff
    }


Sort
    • The order of class extends React.component:

    1. Static Statics method
    2. Constructor
    3. Getchildcontext
    4. Componentwillmount
    5. Componentdidmount
    6. Componentwillreceiveprops
    7. Shouldcomponentupdate
    8. Componentwillupdate
    9. Componentdidupdate
    10. Componentwillunmount
    11. Click Callback or event callback such as Onclicksubmit () or onchangedescription ()
    12. Getter methods in the render function such as Getselectreason () or getfootercontent ()
    13. Optional render methods such as rendernavigation () or renderprofilepicture ()
    14. Render


  • How to define Proptypes, Defaultprops, contexttypes, etc.



    import React, { PropTypes } from ‘react‘;
    
    const propTypes = {
      id: PropTypes.number.isRequired,
      url: PropTypes.string.isRequired,
      text: PropTypes.string,
    };
    
    const defaultProps = {
      text: ‘Hello World‘,
    };
    
    class Link extends React.Component {
      static methodsAreOk() {
        return true;
      }
    
      render() {
        return <a href={this.props.url} data-id={this.props.id}>{this.props.text}</a>
      }
    }
    
    Link.propTypes = propTypes;
    Link.defaultProps = defaultProps;
    
    export default Link;




  • Sort of React.createclass: Eslint:react/sort-comp

    1. DisplayName
    2. Proptypes
    3. Contexttypes
    4. Childcontexttypes
    5. Mixins
    6. Statics
    7. Defaultprops
    8. Getdefaultprops
    9. Getinitialstate
    10. Getchildcontext
    11. Componentwillmount
    12. Componentdidmount
    13. Componentwillreceiveprops
    14. Shouldcomponentupdate
    15. Componentwillupdate
    16. Componentdidupdate
    17. Componentwillunmount
    18. Click Callback or event callback such as Onclicksubmit () or onchangedescription ()
    19. Getter methods in the render function such as Getselectreason () or getfootercontent ()
    20. Optional render methods such as rendernavigation () or renderprofilepicture ()
    21. Render
ismounted
    • Do not use ismounted. eslint:react/no-is-mounted

      Why did you do that? Ismounted is an anti-pattern that is not available when declaring a React component with the ES6 class style and is about to be officially deprecated.


Extended
    • The rules of appeal, you can use the Eslint react plugin to complete the configuration: Eslint-plugin-react, Javascript/packages/eslint-config-airbnb at Master Airbnb/javascript GitHub
    • Fork an official repo, the standard translation here, not only have react, there are two very hot translation version of the ES5 and ES6 rules, strongly recommend not read the people read, you know ES6 is also a very good way. Github-vikingmute/javascript:javascript Style Guide


"Go" Airbnb React code specification


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.