Concise code is more readable, easier to understand, and easier to organize.

This article introduces 6 tips for writing clean code in React.

1. Conditional rendering (when one condition is available)

When you want to render a different component based on a condition, such as if the condition is true, then render the component, otherwise not (render empty content). In this case, do not use the ternary operator, but use the && operator instead. See the following example:

Bad code:

import React, { useState } from 'react'

export const ConditionalRenderingWhenTrueBad = () = > {
  const [showConditionalText, setShowConditionalText] = useState(false)

  const handleClick = () = >
    setShowConditionalText(showConditionalText= >! showConditionalText)return (
    <div>
      <button onClick={handleClick}>Toggle the text</button>
      {showConditionalText ? <p>The condition must be true!</p> : null}
    </div>)}Copy the code

Good code:

import React, { useState } from 'react'

export const ConditionalRenderingWhenTrueGood = () = > {
  const [showConditionalText, setShowConditionalText] = useState(false)

  const handleClick = () = >
    setShowConditionalText(showConditionalText= >! showConditionalText)return (
    <div>
      <button onClick={handleClick}>Toggle the text</button>
      {showConditionalText && <p>The condition must be true!</p>}
    </div>)}Copy the code

2. Conditional rendering (different conditions)

Similar to the previous situation, rendering components are judged based on conditions, except that when conditions are not met, empty content is not rendered, but other component content is rendered.

The ternary operator should be used at this point.

Bad code:

import React, { useState } from 'react'

export const ConditionalRenderingBad = () = > {
  const [showConditionOneText, setShowConditionOneText] = useState(false)

  const handleClick = () = >
    setShowConditionOneText(showConditionOneText= >! showConditionOneText)return (
    <div>
      <button onClick={handleClick}>Toggle the text</button>
      {showConditionOneText && <p>The condition must be true!</p>} {! showConditionOneText &&<p>The condition must be false!</p>}
    </div>)}Copy the code

Good code:

import React, { useState } from 'react'

export const ConditionalRenderingGood = () = > {
  const [showConditionOneText, setShowConditionOneText] = useState(false)

  const handleClick = () = >
    setShowConditionOneText(showConditionOneText= >! showConditionOneText)return (
    <div>
      <button onClick={handleClick}>Toggle the text</button>
      {showConditionOneText ? (
        <p>The condition must be true!</p>
      ) : (
        <p>The condition must be false!</p>
      )}
    </div>)}Copy the code

3. Boolean attributes

We often pass a Boolean property (props) to a component, so writing myTruthyProp={true} is not necessary.

Bad code:

import React from 'react'

const HungryMessage = ({ isHungry }) = > (
  <span>{isHungry ? 'I am hungry' : 'I am full'}</span>
)

export const BooleanPropBad = () = > (
  <div>
    <span>
      <b>This person is hungry: </b>
    </span>
    <HungryMessage isHungry={true} />
    <br />
    <span>
      <b>This person is full: </b>
    </span>
    <HungryMessage isHungry={false} />
  </div>
)
Copy the code

Good code:

import React from 'react'

const HungryMessage = ({ isHungry }) = > (
  <span>{isHungry ? 'I am hungry' : 'I am full'}</span>
)

export const BooleanPropGood = () = > (
  <div>
    <span>
      <b>This person is hungry: </b>
    </span>
    <HungryMessage isHungry />
    <br />
    <span>
      <b>This person is full: </b>
    </span>
    <HungryMessage isHungry={false} />
  </div>
)
Copy the code

It’s a little bit more concise, and it’s just a little trick, but it shows you’re an experienced and good programmer.

4. String properties

This is similar to the previous example, but instead of being a string, we usually enclose the string in double quotation marks and curly braces, as follows:

Bad code:

import React from 'react'

const Greeting = ({ personName }) = > <p>Hi, {personName}!</p>

export const StringPropValuesBad = () = > (
  <div>
    <Greeting personName={"John} "/ >
    <Greeting personName={'Matt'} / >
    <Greeting personName={`Paul`} / >
  </div>
)
Copy the code

Good code:

import React from 'react'

const Greeting = ({ personName }) = > <p>Hi, {personName}!</p>

export const StringPropValuesGood = () = > (
  <div>
    <Greeting personName="John" />
    <Greeting personName="Matt" />
    <Greeting personName="Paul" />
  </div>
)
Copy the code

5. Event binding functions

We often bind a component to an event like onClick or onChange. For example, we might write: onChange={e => handleChange(e)}, which is not necessary.

Bad code:

import React, { useState } from 'react'

export const UnnecessaryAnonymousFunctionsBad = () = > {
  const [inputValue, setInputValue] = useState(' ')

  const handleChange = e= > {
    setInputValue(e.target.value)
  }

  return (
    <>
      <label htmlFor="name">Name: </label>
      <input id="name" value={inputValue} onChange={e= > handleChange(e)} />
    </>)}Copy the code

Good code:

import React, { useState } from 'react'

export const UnnecessaryAnonymousFunctionsGood = () = > {
  const [inputValue, setInputValue] = useState(' ')

  const handleChange = e= > {
    setInputValue(e.target.value)
  }

  return (
    <>
      <label htmlFor="name">Name: </label>
      <input id="name" value={inputValue} onChange={handleChange} />
    </>)}Copy the code

6. Component properties

Similar to the example above, we can also pass components as properties to other components. In this case, we can pass components as functions, but this is not necessary when there are no parameters. See:

Bad code:

import React from 'react'

const CircleIcon = () = > (
  <svg height="100" width="100">
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
  </svg>
)

const ComponentThatAcceptsAnIcon = ({ IconComponent }) = > (
  <div>
    <p>Below is the icon component prop I was given:</p>
    <IconComponent />
  </div>
)

export const UnnecessaryAnonymousFunctionComponentsBad = () = > (
  <ComponentThatAcceptsAnIcon IconComponent={()= > <CircleIcon />} / >
)
Copy the code

Good code:

import React from 'react'

const CircleIcon = () = > (
  <svg height="100" width="100">
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
  </svg>
)

const ComponentThatAcceptsAnIcon = ({ IconComponent }) = > (
  <div>
    <p>Below is the icon component prop I was given:</p>
    <IconComponent />
  </div>
)

export const UnnecessaryAnonymousFunctionComponentsGood = () = > (
  <ComponentThatAcceptsAnIcon IconComponent={CircleIcon} />
)
Copy the code

conclusion

Sometimes when we write code, we don’t notice what’s wrong with the extra line, or the extra content, but sometimes it’s not necessary, and we try to get rid of it, and write better, cleaner code, so that people think you’re an experienced programmer.