Dev. To /adancarrasc… dev. To /adancarrasc…

Adan Carrasco

Translator: Flower fairy

To ensure readability, free translation rather than literal translation is used in this paper. In addition, the copyright of this article belongs to the original author, and translation is for study only. Please contact the author for reprint.

Two weeks ago, I started working on a new project, and some of the code was already written. However, there are no best practices to follow. When you start a new project, it’s important to define together the basics and best practices/guidelines that the team will follow to write the best code: maintainable, easy to read, easy to understand.

I’ll describe five things I saw in the project and how to improve them.

Key word: consistency

1. Import modules in sequence

Introducing ES6 modules in an organized manner will save you time looking for any modules you can’t find or don’t need.

before

import { DatePicker } from '.. /.. /components'
import axios from 'axios'
import { IUser } from '.. /.. /models/User'
import React from 'react'
import { toCamelCase } from '.. /utils'
import { Button } from '@material-ui/core'Copy the code

after

// node_modules
import React from 'react'
import { Button } from '@material-ui/core'
import axios from 'axios'

// Local modules
import { DatePicker } from '.. /.. /components'
import { toCamelCase } from '.. /utils'

// Types + Interfaces
import { IUser } from '.. /.. /models/User'Copy the code

Before the introduction was unordered, a file might not be too cluttered, but trying to find a particular package is really hard when you have a lot of files open. Our team agreed to use the latter approach to group the imported packages, dividing each module by a blank line. Since the files will remain consistent, you can remove the comments.

2. Use deconstruction whenever possible

Another important thing is to prevent unnecessary nesting and duplication. In most cases, readability is greatly improved.

before

const UserProfile = props => (<div>
    <span>{props.firstName}</span>
    <span>{props.lastName}</span>
    <img src={props.profilePhoto}/>
  </div>)Copy the code

after

const UserProfile = ({ firstName, lastName, profilePhoto }) =>
  (<div>
    <span>{firstName}</span>
    <span>{lastName}</span>
    <img src={profilePhoto}/>
  </div>)Copy the code

3. Naming conventions for variables and methods

For code, it is important to know what a method will return, or to easily understand what a variable means by its name (variable semantics), such as

before

let User = {}
User.car = true
User.admin = true

function NewUser() {
  return User
}

function add_photo(photo) {
  user.photo = photo
}
Copy the code

after

let user = {}
user.hasCar = true
user.isAdmin = true

function getUser() {
  return user
}

function setUserPhoto(photoUrl) {
  user.photoUrl = photoUrl
}Copy the code

I later showed how to be consistent in naming variables and methods, and in the following areas:

  • For Boolean types, prefix is, has,should
  • Prefix methods with get/set if the operation props
  • Variables and methods are named hump

4. Prepare your components to receive public variables

before

const UserProfile = props => {
  const { firstName, lastName, profilePhoto } = props
  return (<div>
    <span>{firstName}</span>
    <span>{lastName}</span>
    <img src={profilePhoto}/>
  </div>)
}Copy the code

after

const UserProfile = props => { const { firstName, lastName, profilePhoto, ... rest} = propsreturn(<div {... rest}> <span>{firstName}</span> <span>{lastName}</span> <img src={profilePhoto}/> </div>) }Copy the code

in
afterThe component prepares for injecting public variables such as style, className, key, and so on, passing a set of public attributes into the container using an expansion operation.

Dumb Components make development easier

Creating dumb Components and following the Single Responsibility Principle makes it easy to create and contribute code and keep your codebase clean.

before

import axios from 'axios'

const UserProfile = props => {
  const [user, setUser] = React.useState(null); React.useEffect(() => { getUser(); } []); asyncfunction getUser() {
    try {
      const user = await axios.get('/user/25')
    } catch(error) {
      console.error(error)
    }

    if(user.country === "DE") {
      user.flag = "/de-flag.png"
    } else if(user.country === "MX") {
      user.flag = "/mx-flag.png"
    }
    setUser(user);
  }

  const { firstName, lastName, profilePhoto, userFlag} = user

  return (<div>
    <span>{firstName}</span>
    <span>{lastName}</span>
    <img src={profilePhoto}/>
    <img src={userFlag}>
  </div>)
}Copy the code

after



What might cause problems?

Adding Business Logic to a component can make it difficult to maintain, debug, and test. My recommendation is to make your components presentational components. This way, you can isolate the business logic and focus on testing that component independently. Every previous logic is mixed up. Now let’s separate each responsibility so it’s easier to test and debug.

// userprofilepage. JSX // operate on all UserProfilePage dependencies, adding any additional props or business logic import {fetchUser} from'.. /api'

const UserProfilePage = props => {
  const [user, setUser] = React.useState(null); React.useEffect(() => { getUser(); } []); asyncfunction getUser() {
    const user = fetchUser(error => console.error(error))
    if(user.country === "DE") {
      user.flag = "/de-flag.png"
    } else if(user.country === "MX") {
      user.flag = "/mx-flag.png"
    }
    setUser(user);
  }
  return<UserProfile {... User}/>}/ / api.js // get data and handle errorsexport const fetchUser = async (errorHandler) => {
  try {
    const user = await axios.get('/user/25') retrun user} catch(error) {errorHandler(error)}} // userprofile.jsx // userprofile.jsx as follows const UserProfile = props  => { const { firstName, lastName, profilePhoto, ... rest} = propsreturn(<div {... rest}> <span>{firstName}</span> <span>{lastName}</span> <img src={profilePhoto}/> </div>) }Copy the code



Bonus: If you are using a type checker, make it work.

If your team chooses to use a type checker, it is important to use a strict schema to ensure that it works for the purpose for which it is used.

before

const UserProfile = (props: any) => {
  const { firstName, lastName, profilePhoto, shouldShowPhoto } = props
  return (<div>
    <span>{firstName}</span>
    <span>{lastName}</span>
    <img src={profilePhoto}/>
  </div>)
}Copy the code

after

interface IUserProfile { firstName: string lastName: string profilePhoto: string shouldShowPhoto? : boolean } const UserProfile = (props: IUserProfile) => { const { firstName, lastName, profilePhoto, shouldShowPhoto } = propsreturn (<div>
    <span>{firstName}</span>
    <span>{lastName}</span>
    {shouldShowPhoto && <img src={profilePhoto}/>}
  </div>)
}Copy the code

I’m not saying these rules apply to every project, but your team needs to make their own and agree on them.

What are your best practices/guidelines?

About me

For more technology-related articles, follow the public account “front-end girls juku”.

Add a group reply to join the “Front-end Fairy Group”

You can also scan and add wechat below and note Sol plus front-end exchange group for exchange and learning.