Coding Standards in React Native App.

Sandeep Rajbhar
6 min readApr 8, 2019

--

React Native does not define any coding standard. However, the guidelines in this topic is created by using React Native reference document, online tutorial, blog reference and my expertise in mobility.

Naming Conventions

  • A folder and sub folder name should always start with small letters and the files belong the folders is always in pascal case.
  • To name the components, we follow the pattern path based component naming, which include naming the component accordingly to it’s relative path to the folders components or to src. Basically, a component that is located at: components/common/Button.js would be named as Button.js. Component Name should follow pascal case.
  • When the file is inside a folder with same name, we don’t need to repeat the name. That means, components/user/form/Form.js, would be named as UserForm and not as UserFormForm.
  • Include all the control in single import belong to same module end with semicolon. There should be no space between two imports.

import {ScrollView, View, TouchableOpacity, KeyboardAvoidingView, ListView, AsyncStorage, Alert } from ‘react-native’;

  • Class name should be declare as file name that will be easy during importing and to maintain the standard declaration.
  • The object and variable declaration should always in camel case statement. If we use semicolon then use in all place at end of statement or do not use.

var textExample = “Hello World”;

OR

var textExample = “Hello World”

Layout Conventions

  • Always end a statement with a semicolon.
  • We should create class component when we have to use state otherwise we should use functional component.
  • Not allowing setState() to be invoked on Render() of a React Component.
  • If continuation lines are not indented automatically, indent them one tab stop (four spaces).
  • Add at least one blank line between method and property definitions.
  • There should be no line space between to similar looking statement or similar bunch of code applies for same activity.

const { loading } = this.state;
const { label, scroll, dropdown, disabledLabel } = styles;
const datasources = this.buildDataSource();

And

if (!this.state.isSelctionChange){
this.props.selectedIndex.punchIndex = 0;
this.props.selectedIndex.jobIndex = 0;
}

  • Define arrow functions as class instances and since arrow functions do not have their own scope, this inside arrow function will always point to the class. Therefore you do not need to do binding of this inside constructor. And in most of the cases, you would not be required to use constructor at all. In our project, we never used constructor in any of the components .

Before:

class Button extends Component {
constructor(props) {
super(props);
this.state = { clicked: false };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({ clicked: true });
}
render() {
return <button onClick={this.handleClick}>Click Me!</button>;
}
}

After:

class Button extends Component {
state = { clicked: false };
handleClick = () => this.setState({ clicked: true }); render() {
return <button onClick={this.handleClick}>Click Me!</button>;
}
}

• Object rest spread.
ES6 already supports array spread operator. You can use the same syntax for objects as well. So instead of writing Object.assign({},a,{b:2}), we can directly use {…a, b:2}.
It can make your React code much more beautiful and clean. Let me show you the code before and after using spread operator.

Before:
function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER: return Object.assign({}, state, {
visibilityFilter: action.filter
});
default: return state;
}
}

After:

function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return { …state, visibilityFilter: action.filter };
default: return state;
}
}

  • Refs
    Use ref callback.It’s much more declarative.

Before:

<Welcome ref=”myRef” />

After:

<Welcome ref={(ref) => { this.myRef = ref; }} />

  • On demand render.

This lifecycle method is run before re-rendering process. When a component’s props or state change, React compares new values with rendered one. When they are not equal, React will update the DOM.By default it returns true, leaving React to perform the update. You can use shouldComponentUpdate(nextProps, nextState) and return false by comparing nextProps to rendered (previous) value for halting all the re-rendering of child branches in a component. It can improve performance significantly when you don’t need to re-render a component.

shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) { //By using immutable library we can avoid deep comparison of objects as well
return true;
}
if (this.state.count !== nextState.count) {
return true;
}
return false;
}

  • Other then above layout conventions since react-native support ES6, so we can use all the ES6 feature.

Commenting Conventions

  • Place the comment on a separate line, not at the end of a line of code.
  • Begin comment text with an uppercase letter.
  • End comment text with a period.
  • Insert one space between the comment delimiter (//) and the comment text.

Language Guidelines

Data types:A variable in ReactNative can contain any data. A variable can at one moment be a string and at another be a number

//no error
let message = “hello”;
message = 123456;

A Number:The number type represents both integer and floating point numbers.There are many operations for numbers, e.g. multiplication * , division / , addition +, subtraction — , and so on.

let n = 123;
n = 123.123;

A string:A string in ReactNative must be surrounded by quotes.

let str = “Hello”;
let str2 = ‘Single quotes are ok too’;
let phrase = `can embed ${str}`;

In ReactNative, there are 3 types of quotes.

Double quotes: “Hello”.
Single quotes: ‘Hello’.
Backticks: `Hello`.

Double and single quotes are “simple” quotes. There’s no difference between them in ReactNative.

Backticks are “extended functionality” quotes. They allow us to embed variables and expressions into a string by wrapping them in ${…}, for example:

let name = “John”;
// embed a variable
alert(`Hello, ${name}!`); // Hello, John!
// embed an expression
alert(`the result is ${1 + 2}`); // the result is 3

put anything in there: a variable like name or an arithmetical expression like 1+ 2 or something more complex.Please note that this can only be done in back-ticks. Other quotes don’t have this embedding functionality!

A Boolean:The boolean type has only two values true and false.This type is commonly used to store yes/no values: true means “yes, correct”, and false means “no, incorrect”.For instance:

let nameFieldChecked = true; // yes, name field is checked
let ageFieldChecked = false; // no, age field is not checked

Boolean values also come as a result of comparisons:

let isGreater = 4 > 1;
alert( isGreater ); // true (the comparison result is “yes”)

Literals and properties:

We can immediately put some properties into {…} as “key: value” pairs:

let user = { // an object
name: “John”, // by key “name” store value “John”
age: 30 // by key “age” store value 30
};

Array:There are two syntaxes for creating an empty array:

let arr = new Array();
let arr = [];

Almost all the time, the second syntax is used. We can supply initial elements in the brackets:

let fruits = [“Apple”, “Orange”, “Plum”];

Array elements are numbered, starting with zero.We can get an element by its number in square brackets:

let fruits = [“Apple”, “Orange”, “Plum”];
alert( fruits[0] ); // Apple
alert( fruits[1] ); // Orange
alert( fruits[2] ); // Plum

Props: Props are short for Properties. The simple rule of thumb is props should not be changed. In the programming world we call it “Immutable” or in simple english “Unchangeable”

// Parent
export default class ScreenOne extends React.Component {
render() {
return (
<View>
<Heading message={‘Custom Heading for Screen One’} />
</View>
)
}
}
// Child component
export default class Heading extends React.Component {
render() {
return (
<View>
<Text>{this.props.message}</Text>
</View>
)
}
}
Heading.propTypes = {
message: PropTypes.string
}
Heading.defaultProps = {
message: ‘Heading One’
}

State:State works differently when compared to props. State is internal to a component, while props are passed to a component.

class Form extends React.Component {
constructor(props) {
super(props)
this.state = {
input: ‘’
}
}
handleChangeInput = (text) => {
this.setState({ input: text })
}
render() {
const { input } = this.state
return (
<View>
<TextInput style={{ height: 40, borderColor: ‘gray’, borderWidth: 1 }}
onChangeText={this.handleChangeInput}
value={input}
/>
</View>
)
}
}

Reference link :

Some reference also taken from stack overflow.

--

--

Sandeep Rajbhar
Sandeep Rajbhar

Written by Sandeep Rajbhar

Solution Architect at Royal Cyber.

Responses (2)