• How to Write Cleaner React code
  • By Aditya Tyagi
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: Z Zhaojin
  • Proofreader: zaviertang

How to write simple and elegant React code

Avoid unnecessary labels

After working with more than a dozen production-level React projects, I found that in most cases there was a problem with unnecessary HTML elements or tags. It is important to keep your code easy to maintain, write, read, and debug, and you can use the following methods to determine if your code follows the clean code guidelines.

These unnecessary tags cause DOM pollution. Although these tags were introduced to overcome a weakness of JSX in React (JSX should always return a single HTML root element).

In other words, this is invalid JSX:

// Parentheses are useful for writing multi-line HTML
const element = (
  
  // first div block
  <div>
    <h1>Hello!</h1>
    <h2>Good to see you here.</h2>
  </div>
  // the second div block
  <div>
    <h1>Sibling element</h1>
    <h2>I will break JSX element</h2>
  </div>
);
Copy the code

Many developers solve this problem with JSX by wrapping code blocks with div tags.

const element = (
  
  / / div
  <div>// first div block<div>
        <h1>Hello!</h1>
        <h2>Good to see you here.</h2>
      </div>// the second div block<div>
        <h1>Sibling element</h1>
        <h2>I will break JSX element</h2>
      </div>
  </div>
);
Copy the code

This approach is currently applicable to small projects. When I started developing large React projects, I found that the code was full of div tags. Sooner or later, this will lead to div Soup.

What is thediv soup

Let’s look at an example.

Take a look at the React code:

return (
    // This div does nothing but wrap two child tags around it
    <div>
      <h1>This is heading</h1>
      <h2>This is a sub-heading</h2>
    </div>
  )
Copy the code

The result in the DOM would look like this:

This is just a small example; the real React application is much more complex. You can have a deeply nested parent-child relationship between components. Such as:

return (
    <div>
      <h1>This is heading</h1>
      <h2>This is a sub-heading</h2>
      <Child1>
        <Child2>
          <Child3>
            <Child4/>  
          </Child3>
        </Child2>
      </Child1>
    </div>
  )
Copy the code

Let’s look at the code for the child tag:

// Each React JSX element accepts props parameters
const Child1 = (props) = > (
  <div>
    <h3>I am child 1</h3>{/ *<Child1></Child1>Any content passed between */} {props. Children}</div>
);
const Child2 =  (props) = > (
  <div>
    <h3>I am child 2</h3>
    {props.children}
  </div>
);
const Child3 = (props) = > (
  <div>
    <h3>I am child 3</h3>
    {props.children}
  </div>
);
const Child4 = () = > (
  <div>
    <h3>I am child 4</h3>
  </div>
);
Copy the code

The final DOM will look like this:

If you examine the generated DOM closely, you’ll see a large number of DIV tags that serve no purpose other than to wrap code and overcome JSX limitations. Eventually, this will result in a DIV Soup.

This can increase debugging times exponentially, impacting faster delivery and bug fixes.

How to avoiddiv soup

The eagle-eyed reader must have noticed the solution to the problem code. All we need to do is create a encapsulated React component that returns the pass component without a div:

// Wrap the component, returning any DOM elements passed between 
      
        and 
      
// Props has the children attribute
// All React JSX elements should be capitalized as a naming convention

const Wrapper = (props) = > {
  return props.children;
}
Copy the code

The code before refactoring:

// Children with Wrapper component
// Each React JSX element accepts props parameters
const Child1 = (props) = > (
  <Wrapper>
    <h3>I am child 1</h3>{/ *<Child1></Child1>Any content passed between */} {props. Children}</Wrapper>
);
const Child2 =  (props) = > (
  <Wrapper>
    <h3>I am child 2</h3>
    {props.children}
  </Wrapper>
);
const Child3 = (props) = > (
  <Wrapper>
    <h3>I am child 3</h3>
    {props.children}
  </Wrapper>
);
const Child4 = () = > (
  <Wrapper>
    <h3>I am child 4</h3>
  </Wrapper>
);
Copy the code

At the same time:

// Parent with Wrapper component
return (
    <Wrapper>
      <h1>This is heading</h1>
      <h2>This is a sub-heading</h2>
      <Child1>
        <Child2>
          <Child3>
            <Child4/>  
          </Child3>
        </Child2>
      </Child1>
    </Wrapper>
  )
Copy the code

This will remove unnecessary div tags and prevent div Soup from appearing.

Use the React Fragments could

Introducing the Wrapper component in every React project is difficult and an additional expense that developers want to avoid.

React Fragments introduction.

According to the official documentation:

A common pattern in React is for a component to return multiple elements. Fragments can group lists of child elements without adding additional nodes to the DOM.

— ReactJs.org

This can be done in two ways:

  1. Use the React. Fragments
  2. useReact.Fragment 的Shorthand syntax, i.e.,<></>.

Use code examples to illustrate:

// Use react. Fragment to wrap the Parent component
return (
    <React.Fragment>
      <h1>This is heading</h1>
      <h2>This is a sub-heading</h2>
      <Child1>
        <Child2>
          <Child3>
            <Child4/>  
          </Child3>
        </Child2>
      </Child1>
    </React.Fragment>
  )
Copy the code

It is better to use the react. Fragment shorthand syntax.

// Use the react. Fragment syntax for the Parent component
return (
    <>
      <h1>This is heading</h1>
      <h2>This is a sub-heading</h2>
      <Child1>
        <Child2>
          <Child3>
            <Child4/>  
          </Child3>
        </Child2>
      </Child1>
      
    </>
  )
Copy the code

The final code will look like this:

// Children component with the react. Fragment abbreviation syntax
const Child1 = (props) = > (
  <>
    <h3>I am child 1</h3>{/ *<Child1></Child1>Any content passed between */} {props. Children}</>
);
const Child2 =  (props) = > (
  <>
    <h3>I am child 2</h3>
    {props.children}
  </>
);
const Child3 = (props) = > (
  <>
    <h3>I am child 3</h3>
    {props.children}
  </>
);
const Child4 = () = > (
  <>
    <h3>I am child 4</h3>
  </>
);
Copy the code

This will help you get the same results without div Soup.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.