search
HomeWeb Front-endJS TutorialSeveral advanced methods for decomposing React components

Several advanced methods for decomposing React components

Feb 09, 2018 pm 04:40 PM
reactseveral kindsAdvanced

React components have endless magic and great flexibility. We can play with many tricks in the design of components. But it is very important to ensure the Single responsibility principle of the component: it can make our components simpler and more convenient to maintain, and more importantly, it can make the components more reusable. This article mainly shares with you several advanced methods of decomposing React components, hoping to help you.

However, how to decompose a complex and bloated React component may not be a simple matter. This article introduces three methods of decomposing React components from the shallower to the deeper.

Method 1: Cut render() method

This is the easiest method to think of: when a component renders many elements, you need to try to separate the rendering logic of these elements. The fastest way is to split the render() method into multiple sub-render methods.

It will be more intuitive if you look at the following example:

class Panel extends React.Component {
    renderHeading() {        // ...
    }

    renderBody() {        // ...
    }

    render() {        return (
            <div>
                {this.renderHeading()}
                {this.renderBody()}
            </div>
        );
    }
}

Careful readers will quickly discover that this does not actually decompose the component itself. The Panel component still maintains its original state, props, and class methods.

How to really reduce component complexity? We need to create some subcomponents. At this time, it will definitely be a good try to adopt functional components/stateless components supported and recommended by the latest version of React:

const PanelHeader = (props) => (    // ...);const PanelBody = (props) => (    // ...);class Panel extends React.Component {
    render() {        return (
            <div>                // Nice and explicit about which props are used
                <panelheader></panelheader>
                <panelbody></panelbody>
            </div>
        );
    }
}

Compared with the previous method, this subtle improvement is revolutionary.

We created two new unit components: PanelHeader and PanelBody. This brings convenience to testing, and we can directly test different components separately. At the same time, with the help of React's new algorithm engine React Fiber, the rendering efficiency of the two unit components is optimistically expected to be significantly improved.

Method Two: Template Component

Back to the starting point of the problem, why does a component become bloated and complicated? One is that there are many and nested rendering elements, and the other is that there are many changes within the component, or there are multiple configurations.

At this point, we can transform the component into a template: the parent component is similar to a template and only focuses on various configurations.

I still need to give an example to make it clearer.

For example, we have a Comment component, which has multiple behaviors or events.

At the same time, the information displayed by the component changes according to the user's identity:

  • Whether the user is the author of this comment;

  • Whether this comment is saved correctly;

  • Different permissions

  • etc...

will cause different display behaviors of this component.

At this time, instead of confusing all the logic together, maybe a better approach is to use React to transfer the characteristics of React element. We transfer React element between components, so that it is more like a powerful template. :

class CommentTemplate extends React.Component {
    static propTypes = {        // Declare slots as type node
        metadata: PropTypes.node,
        actions: PropTypes.node,
    };

    render() {        return (            <div>                <commentheading>                    <avatar></avatar>

                    // Slot for metadata                    <span>{this.props.metadata}</span>                </commentheading>                <commentbody></commentbody>                <commentfooter>                    <timestamp></timestamp>

                    // Slot for actions                    <span>{this.props.actions}</span>                </commentfooter>            </div>
            ...
        )
    }
}

At this point, our real Comment component is organized as:

class Comment extends React.Component {
    render() {        const metadata = this.props.publishTime ?        <publishtime></publishtime> :        <span>Saving...</span>;        const actions = [];        if (this.props.isSignedIn) {
            actions.push(<likeaction></likeaction>);
            actions.push(<replyaction></replyaction>);
        }
        if (this.props.isAuthor) {
            actions.push(<deleteaction></deleteaction>);
        }

        return <commenttemplate></commenttemplate>;
    }
}

metadata and actions are actually the React elements that need to be rendered under specific circumstances.

For example:

  • If this.props.publishTime exists, metadata is ;

  • The opposite is Saving....

  • If the user has logged in, it needs to be rendered (that is, the actions value is) and ;

  • If it is the author himself, the content that needs to be rendered must be added with .

Method Three: High-Order Components

In actual development, components are often contaminated by other requirements.

Imagine a scenario like this: We want to count the click information of all links on the page. When the link is clicked, a statistics request is sent, and this request needs to contain the id value of the document of this page.

A common approach is to add code logic to the life cycle functions componentDidMount and componentWillUnmount of the Document component:

class Document extends React.Component {
    componentDidMount() {
        ReactDOM.findDOMNode(this).addEventListener('click', this.onClick);
    }

    componentWillUnmount() {
        ReactDOM.findDOMNode(this).removeEventListener('click', this.onClick);
    }

    onClick = (e) => {        // Naive check for <a> elements        if (e.target.tagName === 'A') { 
            sendAnalytics('link clicked', {                // Specific information to be sent
                documentId: this.props.documentId 
            });
        }
    };

    render() {        // ...
    }
}</a>

Several problems with doing this are:

  • Related component Document In addition to its main logic: displaying the main page, it has other statistical logic;

  • If there is other logic in the life cycle function of the Document component, then this Components will become more ambiguous and unreasonable;

  • statistical logic code cannot be reused;

  • Component reconstruction and maintenance will become more complicated difficulty.

In order to solve this problem, we proposed the concept of higher-order components: higher-order components (HOCs). Without explaining this term obscurely, let’s look directly at how to reconstruct the above code using higher-order components:

function withLinkAnalytics(mapPropsToData, WrappedComponent) {    class LinkAnalyticsWrapper extends React.Component {
        componentDidMount() {
            ReactDOM.findDOMNode(this).addEventListener('click', this.onClick);
        }

        componentWillUnmount() {
            ReactDOM.findDOMNode(this).removeEventListener('click', this.onClick);
        }

        onClick = (e) => {            // Naive check for <a> elements            if (e.target.tagName === 'A') { 
                const data = mapPropsToData ? mapPropsToData(this.props) : {};
                sendAnalytics('link clicked', data);
            }
        };

        render() {            // Simply render the WrappedComponent with all props            return <wrappedcomponent></wrappedcomponent>;
        }
    }
    ...
}</a>

It should be noted that the withLinkAnalytics function does not change the WrappedComponent component itself, let alone Will change the behavior of the WrappedComponent component. Instead, a new wrapped component is returned. The actual usage is:

class Document extends React.Component {
    render() {        // ...
    }
}

export default withLinkAnalytics((props) => ({
    documentId: props.documentId
}), Document);

In this way, the Document component still only needs to care about the parts it should care about, and withLinkAnalytics gives the ability to reuse statistical logic.

The existence of high-order components perfectly demonstrates React’s innate compositional capabilities. In the React community, react-redux, styled-components, react-intl, etc. have generally adopted this approach. It is worth mentioning that the recompose class library makes use of high-order components and carries them forward to achieve "brain-expanding" things.

The rise of React and its surrounding communities has made functional programming popular and sought after. I think the ideas about decomposing and composing are worth learning. At the same time, a suggestion for development and design is that under normal circumstances, do not hesitate to split your components into smaller and simpler components, because this can lead to robustness and reuse.

Related recommendations:

React component life cycle instance analysis

The most complete method to build React components

Detailed explanation of how store optimizes React components

The above is the detailed content of Several advanced methods for decomposing React components. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.