Tuesday, August 2, 2022

React Style Guide

 

Naming

  • Extensions: Use .jsx extension for React components. eslint: react/jsx-filename-extension

  • Filename: Use PascalCase for filenames. E.g., ReservationCard.jsx.

  • Reference Naming: Use PascalCase for React components and camelCase for their instances.

  • Component Naming: Use the filename as the component name. For example, ReservationCard.jsx should have a reference name of ReservationCard. However, 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 './Footer/Footer';
    // bad 
    import Footer from './Footer/index'; 
    // good 
    import Footer from './Footer';

    • Always use camelCase for prop names, or PascalCase if the prop value is a React component.
    • Always define explicit defaultProps for all non-required props.
    • Why? propTypes are a form of documentation, and providing defaultProps means the reader of your code doesn’t have to assume as much. In addition, it can mean that your code can omit certain type checks.

      // bad
      function SFC({ foo, bar, children }) {
        return <div>{foo}{bar}{children}</div>;
      }
      SFC.propTypes = {
        foo: PropTypes.number.isRequired,
        bar: PropTypes.string,
        children: PropTypes.node,
      };
      
      // good
      function SFC({ foo, bar, children }) {
        return <div>{foo}{bar}{children}</div>;
      }
      SFC.propTypes = {
        foo: PropTypes.number.isRequired,
        bar: PropTypes.string,
        children: PropTypes.node,
      };
      SFC.defaultProps = {
        bar: '',
        children: null,
      };
    • Use spread props sparingly.
    Ref: https://github.com/airbnb/javascript/tree/master/react#table-of-contents

    No comments:

    Post a Comment

    Cybersecurity Essential: OpenSSL

    In today’s digital landscape, securing data is paramount. Whether you’re building web applications, managing servers, or developing software...