React Design Patterns and Best Practices(Second Edition)
上QQ阅读APP看书,第一时间看更新

Multi-line

Let's start with a very simple one. As stated previously, one of the main reasons we should prefer JSX over React's createElement function is because of its XML-like syntax, and because balanced opening and closing tags are perfect to represent a tree of nodes.

Therefore, we should try to use it in the right way and get the most out of it.

One example is as follows; whenever we have nested elements, we should always go multiline:

  <div> 
<Header />
<div>
<Main content={...} />
</div>
</div>

This is preferable to the following:

  <div><Header /><div><Main content={...} /></div></div>

The exception is if the children are not elements, such as text or variables. In that case, it makes sense to remain on the same line and avoid adding noise to the markup, as follows:

  <div> 
<Alert>{message}</Alert>
<Button>Close</Button>
</div>

Always remember to wrap your elements inside parentheses when you write them in multiple lines. JSX always gets replaced by functions, and functions written on a new line can give you an unexpected result because of automatic semicolon insertion. Suppose, for example, that you are returning JSX from your render method, which is how you create UIs in React.

The following example works fine because the div element is on the same line as the return:

  return <div />;

The following, however, is not right:

  return 
<div />;

The reason for this is because you would then have the following:

  return; 
React.createElement("div", null);

This is why you have to wrap the statement in parentheses, as follows:

  return ( 
<div />
);