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

Sub-rendering

It is worth stressing that we always want to keep our components very small and our render methods very clean and simple.

However, that is not an easy goal, especially when you are creating an application iteratively, and in the first iteration you are not sure exactly how to split the components into smaller ones. So, what should we be doing when the render method becomes too big to maintain? One solution is to split it into smaller functions in a way that lets us keep all the logic in the same component.

Let's look at an example:

  renderUserMenu() { 
// JSX for user menu
}

renderAdminMenu() {
// JSX for admin menu
}

render() {
return (
<div>
<h1>Welcome back!</h1>
{this.userExists && this.renderUserMenu()}
{this.userIsAdmin && this.renderAdminMenu()}
</div>
);
}

This is not always considered best practice because it seems more obvious to split the component into smaller ones. However, sometimes it helps to keep the render method cleaner. For example, in the Redux real-world examples, a sub-render method is used to render the load more button.

Now that we are JSX power users, it is time to move on and see how to follow a style guide within our code to make it consistent.