Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Programming

    MongoDb. Capped collections

    Programming

    Crafting Interactive User Interfaces Using JavaScript Techniques

    Startups

    Why Startups Fail? Part 2

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Sunday, September 28
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / React / React Lessons / React Lesson 4: Homework. Decorators and Mixins
    JavaScript

    React Lesson 4: Homework. Decorators and Mixins

    Mohammad Shad MirzaBy Mohammad Shad MirzaDecember 19, 2019Updated:December 6, 2024No Comments5 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    React Lesson 4: Homework. Decorators and Mixins
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    As we saw in the previous article, decorators are just the Higher-Order components that add extra functionality to the passed component and return a new enhanced component. Before we get to our homework, let’s dive deep and understand how decorators and mixins work.

    What are decorators?

    Decorators provide a way of calling Higher-Order functions. What are the Higher-Order functions? They simply take a function, modify it and return a new function with added functionality. The key here is that they don’t modify the original function, they simply add some extra functionality which means they can be reused at multiple places. This special feature makes decorators so powerful.

    Note: As decorators are not currently part of JavaScript, the below code snippets cannot be executed in the browser. You can use JSFiddle to execute and understand the below code snippets. In JSFiddle, you have to select the language as Babel + JSX as shown below: https://jsfiddle.net/iamshadmirza/62wgxcdz/1/

    Let’s understand decorators with the help of an example:

    /*
    Let's say we have a room and we want to decorate it with some cool stuff
    It can be written as a function in javascript
    Let's create a poster
    */
    function poster(target){
      target.poster = "Avengers";
    }
    
    //Let's add some wallpaper
    function wallpaper(target){
      target.wallpaper = "Vinyl"
    }
    
    //Let's decorate our room
    //You just have to add the decorator at top of the class
    @poster
    @wallpaper
    class MyRoom {}
    
    console.log(`My room is decorated with an ${MyRoom.poster} poster and has beautiful ${MyRoom.wallpaper} wallpaper`);
    
    /*
    My room is decorated with an Avengers poster and has beautiful Vinyl wallpaper
    */
    
    //Let's assume we want to add owner name also. decorator for that can be created as
    
    function owner(name){
      return function(target){
        target.owner = name;
      }
    }
    
    //Then MyRoom can be defined as
    @poster
    @wallpaper
    @owner("Shad")
    class ShadsRoom {}
    
    //Let's check if it's working
    console.log(`${ShadsRoom.owner}'s room is decorated with ${ShadsRoom.poster} poster and has beautiful ${ShadsRoom.wallpaper} wallpaper`);

    Homework

    Now we can continue with the homework and create a decorator that adds functionality to open one article and close the rest. Let’s create a new file src/decorators/oneOpen.js

    import React, { Component as ReactComponent} from 'react'
     
    export default (Component) => class OneOpen extends ReactComponent {
      state = {
          openItemId: null,
      };
    
      openItem = openItemId => ev => {
        if (ev) ev.preventDefault();
        this.setState({ openItemId });
      }
    
      toggleOpenItem = id => ev => {
        if (ev) ev.preventDefault()
        this.setState({
            openItemId: id === this.state.openItemId ? null : id
        });
      }
    
      isItemOpen = id => this.state.openItemId === id
    
      render() {
        return (
          <Component
            {...this.props}
            isItemOpen={this.isItemOpen}
            openItem={this.openItem}
            toggleOpenItem={this.toggleOpenItem}
          />
        );
      }
    }

    As we discussed earlier in the decorator example, we wrap can any component and decorate it with new functionality which allows us to reuse our code. For example, toggleOpen functionality can be used with comments, authors and other places too. Let’s add this decorator to the ArticleList component.

    Read More:  React Lesson 5: React Devtools and Reusable Open-Source Components

    Using Decorators

    Decorators use a special syntax in JavaScript. They are placed immediately before the code being decorated and prefixed with an @ symbol.

    Note: at the time of writing, the decorators are currently in the “Stage 2 Draft” form, meaning that they are mostly finished but still subject to changes.

    Let’s use the decorator in the ArticleList component.

    1. First, install babel-plugin-transform-decorators-legacy:

    This is important to use the latest syntax for decorators.

    npm install --save-dev babel-plugin-transform-decorators-legacy

    2. Modify ArticleList:

    import React, { Component } from 'react';
    import Article from './Article';
    import oneOpen from './decorators/oneOpen';
    
    // add decorator
    @openOpen
    class ArticleList extends Component {
      renderListItem = () => {
        const { articles, isItemOpen, toggleOpenItem } = this.props;
        return articles.map((article) => (
          <li key={article.id}>
            <Article
              article={article}
              isOpen={isItemOpen(article.id)}
              openArticle={toggleOpenItem(article.id)}
            />
          </li>
        ));
      };
    
      render() {
        return (
          <div>
            <h1>Article list</h1>
            <ul>
              {this.renderListItem()}
            </ul>
          </div>
        );
      }
    }
    
    export default ArticleList;

    Alternate way:

    If you want to go with the traditional decorator pattern as function wrapper, you can simply do:

    // imports and class code above
    export default oneOpen(ArticleList);

    Remove @oneOpen above class and wrap class with the decorator. That’s it.

    Mixins

    Mixins are another way of sharing code between multiple components. The commons functionalities like openItem, toggleOpenItem, etc can be extracted to mixins and reused at different places.

    Create a file src/mixins/oneOpen.js

    export default {
        getInitialState() {
          return {
            openItemId: false
          }
        },
        openItem(openItemId) {
          return ev => {
            if (ev) ev.preventDefault()
            this.setState({openItemId});
          }
        },
     
        toggleOpenItem(id) {
          return ev => {
            if (ev) ev.preventDefault();
            this.setState({
              openItemId: id === this.state.openItemId ? null : id
            });
          }
        },
     
        isItemOpen(id) {
          return this.state.openItemId === id;
        }
    }

    Mixins are only compatible with React.createClass and not with the new ES6 class constructor. React.createClass has been moved to a separate module so let’s quickly install that:

    npm i create-react-class

    Let’s update the ArticleListOld  with the mixin we just created:

    import React, { Component }  from 'react';
    import Article from './Article';
    import oneOpen from './mixins/oneOpen'
    import createReactClass from "create-react-class";
     
    const ArticleList = createReactClass ({
        mixins: [oneOpen],
        render() {
            const { articles } = this.props
            const listItems = articles.map((article) => <li key={article.id}>
                <Article article = {article}
                    isOpen = {this.isItemOpen(article.id)}
                    openArticle = {this.toggleOpenItem(article.id)}
                />
            </li>)
            return (
                <div>
                    <h1>Article list</h1>
                    <ul>
                        {listItems}
                    </ul>
                </div>
            )
        }
    });
     
    export default ArticleList;

    Note: Mixins are deprecated and replaced with better and more powerful Higher-Order components which are basically decorators. React community encourages that you use HOC instead of mixins at all time. https://reactjs.org/blog/2015/01/27/react-v0.13.0-beta-1.html#mixins

    This was to illustrate the use of mixins. We will only use decorators in the future.

    Read More:  JavaScript find() and filter() Array Iteration Methods Made Easy

    Conclusion

    Higher-Order Component and decorator patterns are powerful methods to reuse code at different places. Currently, they are widely used and are a replacement for old mixin syntax. You can still create your mechanism for dealing with mixing functionality between components.

    You can check out the live playground of today’s lesson in the codesandbox below.

    Edit React_lesson_lesson4

    Reference:

    • Exploring ECMAScript Decorators: https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841
    • ECMAScript proposals: https://github.com/tc39/proposals#stage-2
    • Mixins considered harmful: https://reactjs.org/blog/2016/07/13/mixins-considered-harmful.html

    Please compare our code with yours, and we will go further. Please check this repository for the right commits.

    Previous lessons can be viewed here: https://blog.soshace.com/category/javascript/react/react-lessons/

    435258_8a75_3

     

    JavaScript js programming react react lessons webdev
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Mohammad Shad Mirza
    • X (Twitter)
    • LinkedIn

    JavaScript lover working on React Native and committed to simplifying code for beginners. Apart from coding and blogging, I like spending my time sketching or writing with a cup of tea.

    Related Posts

    Streamlining Resource Allocation for Enhanced Project Success

    December 18, 2024

    Conducting Effective Post-Project Evaluations: A Guide

    December 16, 2024

    Strategies for Keeping Projects on Track and Meeting Deadlines

    December 10, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    Machine Learning April 5, 2023

    NLP Preprocessing using Spacy

    I have worked on a number of NLP projects and after collecting the data the biggest challenge is the pre-processing. Since the text data available on the internet is often highly unstructured, contains unwanted symbols, repeated characters, contains different forms of the same root word, etc.

    7 Job Recruitment Trends 2019 | From Self-Service Modules to Peculiarities of Gen Z

    April 17, 2019

    Build Real-World React Native App #8 : implement Dark mode

    December 29, 2020

    Mastering Common Interview Questions: Strategic Responses Guide

    November 29, 2024

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    React Lesson 7: Redux

    JavaScript January 10, 2020

    SMART Financial Goals for Remote Workers

    Remote Job January 28, 2019

    Memory Leaks in Java: A Cautionary Tale and Gentle Introduction to Preventing Memory Errors

    Java December 26, 2019

    This Is How I Created a Simple App Using React Routing

    JavaScript February 19, 2020

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    JavaScript

    Create simple POS with React.js, Node.js, and MongoDB #17: Stat screen

    LinkedIn

    Strategies for Identifying High-Quality LinkedIn Prospects by Niche

    JavaScript

    Essential Steps for Crafting a Comprehensive Project Charter

    Most Popular

    Web Usability Essentials

    Beginners

    How to Create a Personal Blogging Website: Back-End (Flask/Python) #1

    Angular

    2. Express.js Lessons. Logger, Configuration, Templating with EJS. Part 1.

    Programming
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.