Table of Contents
Method 1: Cut render() method
Method Two: Template Component
Method Three: High-Order Components
Home Web Front-end JS Tutorial Several advanced methods for decomposing React components

Several advanced methods for decomposing React components

Feb 09, 2018 pm 04:40 PM
react several kinds Advanced

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

class Panel extends React.Component {

    renderHeading() {        // ...

    }

 

    renderBody() {        // ...

    }

 

    render() {        return (

            <div>

                {this.renderHeading()}

                {this.renderBody()}

            </div>

        );

    }

}

Copy after login

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:

1

2

3

4

5

6

7

8

9

const PanelHeader = (props) => (    // ...);const PanelBody = (props) => (    // ...);class Panel extends React.Component {

    render() {        return (

            <div>                // Nice and explicit about which props are used

                <PanelHeader title={this.props.title}/>

                <PanelBody content={this.props.content}/>

            </div>

        );

    }

}

Copy after login

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. :

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

class CommentTemplate extends React.Component {

    static propTypes = {        // Declare slots as type node

        metadata: PropTypes.node,

        actions: PropTypes.node,

    };

 

    render() {        return (            <div>                <CommentHeading>                    <Avatar user={...}/>

 

                    // Slot for metadata                    <span>{this.props.metadata}</span>                </CommentHeading>                <CommentBody/>                <CommentFooter>                    <Timestamp time={...}/>

 

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

            ...

        )

    }

}

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

class Comment extends React.Component {

    render() {        const metadata = this.props.publishTime ?        <PublishTime time={this.props.publishTime} /> :        <span>Saving...</span>;        const actions = [];        if (this.props.isSignedIn) {

            actions.push(<LikeAction />);

            actions.push(<ReplyAction />);

        }

        if (this.props.isAuthor) {

            actions.push(<DeleteAction />);

        }

 

        return <CommentTemplate metadata={metadata} actions={actions} />;

    }

}

Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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() {        // ...

    }

}

Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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 {...this.props} />;

        }

    }

    ...

}

Copy after login

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:

1

2

3

4

5

6

7

8

class Document extends React.Component {

    render() {        // ...

    }

}

 

export default withLinkAnalytics((props) => ({

    documentId: props.documentId

}), Document);

Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
How to build a reliable messaging app with React and RabbitMQ How to build a reliable messaging app with React and RabbitMQ Sep 28, 2023 pm 08:24 PM

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

What closures does react have? What closures does react have? Oct 27, 2023 pm 03:11 PM

React has closures such as event handling functions, useEffect and useCallback, higher-order components, etc. Detailed introduction: 1. Event handling function closure: In React, when we define an event handling function in a component, the function will form a closure and can access the status and properties within the component scope. In this way, the state and properties of the component can be used in the event processing function to implement interactive logic; 2. Closures in useEffect and useCallback, etc.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

Advanced PHP Programming: Design and Implementation of Like Function for Multiple Articles Advanced PHP Programming: Design and Implementation of Like Function for Multiple Articles Feb 28, 2024 am 08:03 AM

As a PHP developer, we often encounter the need to add a like function to a website or application. This article will introduce how to design and implement a multi-article like function through advanced PHP programming, and provide specific code examples. 1. Functional requirements analysis Before designing the function of liking multiple articles, we first need to clarify our functional requirements: users can view multiple articles on the website and like each article. Users can only like each article once. Once the user has already liked the article, they cannot like it again. use

See all articles