fredywhatley
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # RoomsToGo React Style Guide *A mostly reasonable approach to achieve consitentcy and maintenance speed in React* ## Table of Contents 1. [Component Folder Structure](#component-folder-structure) 1. [Basics](#basics) 1. [Passing Props or Push Props Up](#passing-props-or-push-props-up) 1. [Imports](#imports) 1. [Constants](#constants) 1. [Styling](#styling) ## Component Folder Structure - use dot notation with all lowercase letters for all folders and files > Why? It's very clear that is the same casing. No one will ever spend time guessing how to name these: folders & files like js, images, css, json, tests, stories, and others ``` // bad / App.css |-- / Images |-- / components |--|- / ProductDetailsView.js |--|- / productDetailsImage.jpeg |--|- / RTGButton.js |--|- / RtgButton.tests.js |--|- / sale-flag.js |--|- / sale-flag.stories.js // good / app.css |-- / images |-- / components |--|--|-- / product.details |--|--|--|-- / product.details.view.js |--|--|--|-- / product.details.image.jpeg |--|--|-- / rtg.button |--|--|--|-- / rtg.button.js |--|--|--|-- / rtg.button.tests.js |--|--|-- / sale.flag |--|--|--|-- / sale.flag.js |--|--|--|-- / sale.flag.stories.js ``` - create a folder for each component which will contain the component and its helper files like styles, constants, and others. > Why? components tend to grow so we want to be able to extract styles, constants and others into separate files for faster refactor later. Big files are harder to refactor because there is too much code noise, and you have to scroll up & down the editor. ``` // bad |-- / components |--|-- / swiper.js // good |-- / components |--|-- / swiper |--|--|-- / index.js |--|--|-- / swiper.js |--|--|-- / swiper.styles.js |--|--|-- / swiper.constants.js // other files can be added as well ``` Components can be **compound** like dialog, tabs, etc. Compound components consist of many smaller related components and it's fine to place them within one file or same component folder ``` // good |-- / dialog |--|- / index.js |--|- / dialog.js // may have DialogTitle, DialogFooter |--|- / dialog.styles.js |--|- / dialog.content.js // exports DialogContent |--|- / dialog.constants.js // other files can be added as ``` Components can be **derived** like button and apple-button, Dialog and AlertDialog. Derived component is specialization of basic component with extra logic/styles/behavior and it's important to keep derived components separated from main implementation. ``` // bad |-- / button |--|- / index.js |--|- / button.js |--|- / apple.button.js ``` ``` // good |-- / button |--|- / index.js |--|- / button.js |-- / button |--|- / apple.button.js ``` ## Basics - name the component the same as the file name ```jsx // bad // inside swiper.js function SimpleSwiper(props) { // ... } // good // inside swiper.js function Swiper(props) { // ... } ``` - include `index.js` inside component folder, which should only re-export and do nothing else > Why? allows encapsulation, shorter imports - always use propTypes ## Passing Props or Push Props Up - make sure props being passed to a component should be first and the props being pushed up should be last - make sure props pushed up have a prefix of on-* so it’s known what that prop is doing ```jsx // bad <ExampleComponent passedData={data.this} handleFocus={onFocusEffect} onBlur={onBlurEffect} passedDataAgain={data.here} /> // good <ExampleComponent passedData={data.this} passedDataAgain={data.here} onFocus={onFocusEffect} onBlur={onBlurEffect} /> ``` - when you are actually calling the prop function you don’t need to add the prefix ```jsx // good <ExampleComponent passedData={data.this} passedDataAgain={data.here} onFocus={focusValidation} onBlur={handleBlur} /> ``` ## Imports - organize imports in this order **import node modules**: display node modules first **import common code**: display common code second **import component code**: display component code third ```jsx // bad // inside select.room.tile.js import THEME from '../theme import React from 'react' import EMPTY_ROOM_TEXT from './select.room.tile.constants' import PropTypes from 'prop-types' import Card from '@material-ui/core/Card' function SelectRoomTile(props) { // ... } // good // inside select.room.tile.js import React from 'react' import PropTypes from 'prop-types' import Card from '@material-ui/core/Card' import THEME from '../theme' import Button from '../button' import EMPTY_ROOM_TEXT from './select.room.tile.constants' function SelectRoomTile(props) { // ... } ``` ## Constants - SNAKE_CASE all constants - place constant string/number/objects values inside a constant or state file instead of inside the component Perfect candidates for these are static data for stories and tests. Other candidates are static skus, messages, min/max allowed numbers > Why? allows to update value in a single place, allows to re-use constant in other components, tests, stories, and others ## Hook rules and patterns - Always try to idenity reuseable hook primitives with meaningful name and single purpose. For instance: useIsHovered, useMousePosition, useBattery - Do not put a lot of hook code within component. If you have a lot of custom logic create separate hook named useComponentData(args) - Keep reuseable hook within src/hooks folder at root level - Avoid passing refs to components and subscribing to events. For isntance if you need to monitor if component is focused it's much easier to implement this hook with props getter pattern rather with passing refs. ```jsx // bad function useHovered(ref) { const [state, setState] = useState() useEffect(()=>{ // and same for mouseout function onSubscribe(event) { setState(v=>true); } ref.current.addEventListener("mouseover", onSubscribe); return ()=>{ ref.current.removeEventListener(onSubscribe); } }, []) return {isHovered} } ``` ```jsx // good function useHovered() { const [state, setState] = useState() const onMouseover = useCallback((event)=>{ setState(true) },[]) const onMouseout = useCallback((event)=>{ setState(false) },[]) return {isHovered:state, getProps: ()=>({ onMouseover, onMouseout })} } // within component function Button() { const {isHovered, getProps} = useHovered() return <button {...getProps()} /> } ``` This way your component will be just thin wrapper which creates event handlers for component. This way you don't need to forwardRefs, you are in control of execution order and implementation is much simplier. This is quite popular pattern in libraries like react-table and downshift. ## Testing rules and patterns - Create testing actions which help you to write tests on more higher level of abstraction. ```jsx // as you can see this way tests became much more self expanantory // at the same time it's easy to modify them. test("datepicker", async ()=>{ // all dom nodes variables have $ sign at begining. // query datepicker input on page const $datepickerInput = screen.getByTestId("datepicker"); // open datepicker popup await openDatepickerModal($datepickerInput); // get reference to datepicker const $datepicker = await getDatepicker($datepickerInput) // set selected days on datepicker await setSelectedDays($datepicker, 5) // get specific days on datepicker const days = await getSelectedDays($datepicker); expect(days.length).toEqual(5); }) ``` - Create render function for common logic instead of beforeEach ```jsx function renderComponent(optionalParams) { const mockFn = jest.fn(); const testApi = render(<Provider><MyComponent onClick={mockFn}/></Provider>) return { ...testApi, onClickMocked: mockFn // ...etc } } test("it works", async()=>{ const {findByText} = renderComponent(); await findByText("something") }) ``` Why? This way it's much easier to create several reuseable render function for different use cases. For instance test my component for different layouts, you can do that really easily with shared render functions and it looks much more complex with before each. - Follow guides from testing-library https://testing-library.com/docs/guiding-principles - More info https://kentcdodds.com/blog/?q=testing ## Global Styling - TODO: global styling: theme vs tokens (constants) ## Component Styling - Prefer object syntax over styled tag syntax ```jsx const StyledButtonBad = styled.div` color: red; ` const StyledButtonGood = styled.div(()=>({ color: "red" })) ` ``` Why? We need to be consistent at styles definitions and object syntax is the least evil. Working with objects is much more simpler and easier to migrate from one library to another. **[⬆ back to top](#table-of-contents)**

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully