Coding conventions and standards are an integral part of any software engineering project. Various software developers working on different modules of the same software could lead to ambiguity in code and understanding of a particular function. Conventions form a sort of base and guideline to keep the project as uniform as possible even with multiple programmers. It brings structure to the code and makes it synchronous. It also makes it easier for one programmer to read another programmer’s code. They are a set of guidelines which cover various aspects of a programming language such as:
- Indentation
- Comments
- Variable names
- Declarations
- White space
- Naming conventions
Following coding conventions greatly reduces the cost of maintaining the software. It improves the readability of the software which allow a programmer/engineer to understand new code quickly. It also helps manage complexity of a project.
- Only include one React component per file
- Use JSX syntax
- Do not use React.createElement() unless the app is being initialized from a non-JSX file.
-
For internal states and refs prefer using class extends React.Component over React.createClass
// 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>; } }
-
Use normal functions over classes if there are no states or refs
// bad class Listing extends React.Component { render() { return <div>{this.props.hello}</div>; } } // bad (since arrow functions do not have a "name" property) const Listing = ({ hello }) => ( <div>{hello}</div> ); // good function Listing({ hello }) { return <div>{hello}</div>; }
-
Use .jsx extension for React components
-
Use PascalCase for filenames. For example,
WidgetToDo.jsx
-
User PascalCase for React components and camelCase for their instances
// bad import todoItems from './todoItems'; // good import TodoItems from './TodoItems'; // bad const TodoItems = <TodoItems />; // good const todoItems = <todoItems />;
-
To name components, use the filename itself as the name of the component.
WidgetToDo.jsx
should have a reference name ofWidgetToDo
. -
For root components of a directory, use
index.jsx
as the filename and use the directory name as the component name.// bad import Footer from './TodoItems/TodoItems'; // bad import Footer from './TodoItems/index'; // good import Footer from './TodoItems';
-
Name components by reference and not through displayName.
// bad export default React.createClass({ displayName: 'TodoItems', // stuff goes here }); // good export default class TodoItems extends React.Component { }
-
Follow the alignment styles for JSX.
// bad <Foo superLongParam="one" anotherSuperLongParam="two" /> // good <Foo superLongParam="one" anotherSuperLongParam="two" /> // if props fit in one line then keep it on the same line <Foo bar="bar" /> // children get indented normally <Foo superLongParam="one" anotherSuperLongParam="two" > <Quux /> </Foo>
-
Must use double quotes (“) for JSX attributes but single quotes (‘) for all other JS.
// bad <Foo bar='bar' /> // good <Foo bar="bar" /> // bad <Foo style={{ left: "10px" }} /> // good <Foo style={{ left: '10px' }} />
-
Include single space in a self-closing tag
// bad <Foo/> // very bad <Foo /> // bad <Foo /> // good <Foo />
-
Use camelCase for prop names
// bad <Foo UserName="John" phone_number={12345678} /> // good <Foo userName="John" phoneNumber={12345678} />
-
If the prop is true, remove the explicit mention.
// bad <Foo hidden={true} /> // good <Foo hidden />
-
If JSX tags span more than one line, wrap using parentheses.
// bad render() { return <MyComponent className="long bod" 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>; }
-
Always self close tags that have no children.
// bad <Foo className="asset"></Foo> // good <Foo className="asset" />
-
If the component is multi-line, close the tag on a new line.
// bad <Foo bar="bar" baz="baz" /> // good <Foo bar="bar" baz="baz" />
-
Use arrow functions to close instead local variables.
function ItemList(props) { return ( <ul> {props.items.map((item, index) => ( <Item key={item.key} onClick={() => doSomethingWith(item.name, index)} /> ))} </ul> ); }
-
Use event handlers for the render method in the constructor.
// 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} /> } }
-
For internal methods of a React component, do not use the underscore prefix.
// bad React.createClass({ _onClickSubmit() { // do stuff }, // other stuff }); // good class extends React.Component { onClickSubmit() { // do stuff } // other stuff }
- Ordering for
class extends React.Component
:
- optional
static
methods constructor
getChildContext
componentWillMount
componentDidMount
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
componentWillUnmount
- clickHandlers or eventHandlers like
onClickSubmit()
oronChangeDescription()
- getter methods for
render
likegetSelectReason()
orgetFooterContent()
- Optional render methods like
renderNavigation()
orrenderProfilePicture()
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;
-
Ordering for
React.createClass
: eslint:react/sort-comp
displayName
propTypes
contextTypes
childContextTypes
mixins
statics
defaultProps
getDefaultProps
getInitialState
getChildContext
componentWillMount
componentDidMount
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
componentWillUnmount
- clickHandlers or eventHandlers like
onClickSubmit()
oronChangeDescription()
- getter methods for
render
likegetSelectReason()
orgetFooterContent()
- Optional render methods like
renderNavigation()
orrenderProfilePicture()
render
- Use camelCase for variable and function names
- Begin all names with letters.
firstName = "Barkha";
lastName = "Bhojak";
price = 19.90;
tax = 0.20;
fullPrice = price + (price * tax);
- Put a space around operators such as =,+,-,/,* and after commas
var x = y + z;
var values = ["Hello", "World", "Smile"];
- End simple statements with semicolons
var values = ["Hello", "World", "Smile"];
var person = {
firstName: "Barkha",
lastName: "Bhojak",
eyeColor: "brown"
};
- Put the opening bracket at the end of the first line
- A space is necessary before the opening bracket
- The closing bracket should be placed on a new line without leading space
function summation(a,b) {
return a + b;
}
- The opening bracket should be placed on the same line as the object name
- Each property should be defined with a colon and one space between the name and value.
- Do not use quotes around numeric values
- A closing bracket should be places on the next line without elading spaces
- End the object definition with a semicolon
- Objects that are short can be written in one line using spaces between properties.
var person = {
firstName: "Barkha",
lastName: "Bhojak",
eyeColor: "brown"
};
var person = {firstName:"Barkha", lastName:"Bhojak", eyeColor:"brown"};
- Try to avoid lines greater than 120 characters
- If it does not fit in one line, break it.
-
Declare the document type as the first line of the document always
<!DOCTYPE html>
-
Avoid mixing upper and lowercase names
<section> <p>This is a paragraph.</p> </section>
-
Even though it is not required, ensure closure of all elements
<section> <p>This is a paragraph.</p> <p>This is a paragraph.</p> </section>
-
Also close all empty elements. The slash (/) is required in XML.
<meta charset="utf-8" />
-
Use quotes if the value contains spaces. It makes it easier to read.
<table class="table striped">
- Airbnb React/JSX Style Guide
- Javascript and HTML Style Guide