Skip to content

Instantly share code, notes, and snippets.

@kleviscipi
Last active March 14, 2022 17:07
Show Gist options
  • Select an option

  • Save kleviscipi/af2e1488507d1acd294da1b46779fd07 to your computer and use it in GitHub Desktop.

Select an option

Save kleviscipi/af2e1488507d1acd294da1b46779fd07 to your computer and use it in GitHub Desktop.
Standards recommendation for JSX,JavaScript code

Define variables

  • Local variables must be defined in camelCase starting with lowercase like, without underscores and without numbers:
  • Should be used let instead of var
    function getDetails(){
        let name = 'React'
        let version = 'V1'
        ...
    }
  • Global variables must be defined in uppercase dividing meaning words with underscores without containing numbers:
    let USER = 0;
    let AGE = 100 

    let USER_COUNT = 0;
    let MAX_USER_AGE = 100;
  • A constant variable of a class or global must be defined in uppercase dividing meaning words with underscores without containing numbers.
    const STATUS = 1;
    const MAX_USER_AGE_PERMITED = 50;
  • Arguments of a method
    • should be defined in lowercase dividing meaning words by underscores
    • each, should be separated by a space after the comma
    • can contain numbers but can not start with numbers
   //Good
   function(argument_1, argument_2, total_users){
       // content here
   }
   
   //Bad
   function(1_argument,argument_2,totalUsers){
       // content here
   }

Statements, Braces, Spaces, Indent, Horizontal and Vertical defining code

  • Braces must start at the same line of the defined name of (class, method, statement) and end at the same vertical line of start name:
    //Good

    function getUserCount(){ // Start Braces
        ....
        if(true){
            ....
        }

    } // End of Braces

    //Bad
    function getUserCount()
    { // Start Braces
        ....
        if(true) 
        {
            ....
        }
    } // End of brackets

    function getUserCount()
    { // Sart Braces
        .... } // End of Braces
    
  • Defined methods, classes must be divided by a space from which-other:
    // Good
    getUserCount(){
        ....
    }

    getUserAge(){
        ....
    }

    //Bad: two methods are not divided by a space in vertical.
    getUserCount(){
        ....
    }
    getUserAge(){
        ....        
    }
  • Indent must contain four (4) spaces, and must be used the [tab] for indents:
    if(true){
    // the tab rapresent four spaces
    [tab]let user = null;
    [tab]let age = 30;

    }
  • Variables which are defined in vertical and have approximately the same space in a horizontal way should be indented in a readable view, like this:
    //Good
    let idUser    = 10;
    let total     = 11;
    let ageUser   = 50;

    //Bad
    let idUser = 10;
    let total = 11;
    let ageUser = 50;
  • Variables which are defined in vertical, but doesn't have approximately the same space in a horizontal way, should be indented in a readable view, like this:
    //Good
    let id = 1;
    let totalStandartUser = 10
    let maxAgeInRoomDiscusionUsers = 10

    //Bad
    let id                         = 1;
    let totalStandartUser          = 10
    let maxAgeInRoomDiscusionUsers = 10
  • Defined Local (just local) variables that have the same initial value should be defined in horizontal lines.
  • Note: The main reason using this rule is to reduce the vertical space.
    // Good
    let ids = userAges = list = []; 
    let status = debug = 0;

    // Bad
    let ids        = [];
    let userAges   = [];
    let list       = [];

    let status = 0;
    let debug = 0;

Jsx ShortHand props

    // Good:
    return (
        <Navbar showTitle />
    );

    // Bad
    return (
        <Navbar showTitle={true} />
    );

Ternary Operator

    // Good:
    const { role } = user;
    return role === ADMIN ? <Admin /> : <User />

    // Bad:
    const { role } = user;

    if(role === ADMIN) {
        return <Admin />
    }else{
        return <User />
    }

Object Literals ?

        const {role} = user

        const components = {
            ADMIN: AdminUser,
            EMPLOYEE: EmployeeUser,
            USER: NormalUser
        };

        const Component = components[role];

        return <Componenent />

    // Bad:
    
        const {role} = user

        switch(role){
            case ADMIN:
                return(<AdminUser />)
            case EMPLOYEE:
                return(<EmployeeUser />)
            case USER:
                return(<NormalUser />)

Fragments instead of div

    // Good:
    return (
        <>
            <Component1 />
            <Component2 />
        </>  
    )
    //OR
    return (
        <React.Fragment>
            <Component1 />
            <Component2 />
        </React.Fragment>
    )

    // Bad:
    return (
        <div>
            <Component1 />
            <Component2 />
        </div>  
    )

Don't define functions inside render

    // Good
    const submitData = () => dispatch(ACTION_TO_SEND_DATA)

    return (
        <button onClick={submitData}>  
            Send
        </button>  
    )
    
    // Bad
    return (
        <button onClick={() => dispatch(ACTION_TO_SEND_DATA)}> 
            Send
        </button>  
    )

Use React.memo on this situation:

  • You can use Pure Components instead but if components are pure functional components you should use memo than:
    • Pure functional component The <Component> is functional that given the same props and always render the same output
    • <Component> render often
    // For example here is a case to use the React.Memo
    export function Movie({ title, releaseDate }) {
        return (
            <div>
                <div>Movie title: {title}</div>
                <div>Release date: {releaseDate}</div>
            </div>
        );
    }

    export const MemoizedMovie = React.memo(Movie);


    function MovieViewsRealtime({ title, releaseDate, views }) {
        return (
            <div>
                <Movie title={title} releaseDate={releaseDate} />
                Movie views: {views}
            </div>
        );
    }

    // Initial render
    <MovieViewsRealtime 
        views={0} 
        title="Forrest Gump" 
        releaseDate="June 23, 1994" 
    />

    // After 1 second, views is 10
    <MovieViewsRealtime 
        views={10} 
        title="Forrest Gump" 
        releaseDate="June 23, 1994" 
    />

    // Every time is called MovieViewsRealtime the component Movie is rendered to but is no nead to render that compoment because just the value of the prop views is changing and that value is used by just by MovieViewsRealtime.

    // So we should use the React.memo to increase the performance of project.

Css:

  • if there is more than 3 attributes of css in line you should use a className must be used literal objects non inline style coding

        //Good:
            const styleDiv = {display:'block'}
            return <div style={syleDiv}> ... </div>
    
        //Bad:
            return <div style={{display:'block'}}> ... </div>

Object Destructuring

    // Good:
        const {name,age,profession} = this.props.user
        return (
            <>
                <div> {name} </div>
                <div> {age} </div>
                <div> {profession} </div>
            </>  
        )
    // Bad:
        const user = this.props.user
        return (
            <>
                <div> {user.name} </div>
                <div> {user.age} </div>
                <div> {user.profession} </div>
            </>  
        )

Do not use curly braces on props string when passing to <Component>

    // Good:
        return(
            <Head title="My Title" />
        )

    // Bad:
        return(
            <Head title={"My Title"} />
        )

Do not use Javascript code directly to tags or react compoments

    // Bad
    return (
        <ul>
            {users.map((user) => (
                <li onClick={event => {
                    console.log(event.target, 'clicked!');
                }} key={user.id}>{user.title}
                </li>
            ))}
        </ul>
    );

    // Good
    const onClick = (event) => {
        console.log(event.target, 'clicked!'); 
    }
    return (
        <ul>
            {users.map((user) => (
                <li onClick={onClick} key={user.id}>{user.title}</li>
            ))}
        </ul>
    );

Template literals

    // Good
    const userDetails = `${user.name}'s profession is ${user.proffession}`

    return (
        <div> {userDetails} </div>  
    )
    
    // Bad
    const userDetails = user.name + "'s profession is" + user.proffession

    return (
        <div> {userDetails} </div>  
    )

Import in order as possible:

  • Rules:
    • Build-In imports
    • External imports
    • Internal imports
    // Good
    import React from 'react';

    import { PropTypes } from 'prop-types';
    import styled from 'styled-components/native';

    import ErrorImg from '../../assets/images/error.png';
    import colors from '../../styles/colors';

    // Bad
    import React from 'react';
    import ErrorImg from '../../assets/images/error.png';
    import styled from 'styled-components/native';
    import colors from '../../styles/colors';
    import { PropTypes } from 'prop-types';

Component Naming

  • Use PascalCase naming for components
    //Good
    import ReservationCard from './ReservationCard';
    //Bad
    import reservationCard from './ReservationCard';

Quotes

    // Good
    <Foo bar="bar"/>
    <Foo style={{ left: '20px' }} />

    // Bad
    <Foo bar='bar' />
    <Foo style={{ left: "20px" }} />

Prop Naming

  • use camelCase for props names
  • use PascalCase if prop value is a ReactComponent
    // Good
    <MyComponent
        userName="hello"
        phoneNumber={12345678}
        Component={SomeComponent}
    />
    // Bad
    <Component
        UserName="hello"
        phone_number={12345678}
        component={SomeComponent}
    />

Use Parentheses if JSX component return have more tha one line

    // Good
    return (
        <MyComponent variant="long">
            <MyChild />
        </MyComponent>
    );

    // Bad
    return <MyComponent variant="long">
            <MyChild />
        </MyComponent>;

Do not use underscores in Method Name

    // Good
    const onClickHandler = () => {
        ...
    }
    // Bad
    const _onClickHandler = () => {
        ...
    }

Methods inside a class should be bind in constructor

    //Good
    class User extends React.Component{
        constructor(){
            this.state = {}
            this.onChange = this.onChange.bind(this)
        }

        onChange(e){
            ...
        }
        render(){
            return <input type='text' onChange={this.onChange} />
        }
    }
    // Bad

    class User extends React.Component{
        constructor(){
            this.state = {}
        }

        onChange(e){
            ...
        }
        render(){
            return <input type='text' onChange={this.onChange.bind(this)} />
        }
    }
  • Defining max 4 arguments for methods
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment