ScandiPWA
Create Magento AppCreate ScandiPWA AppUser ManualGitHub
  • Why Scandi
  • πŸš€Quick-start Guide
  • πŸ—ΊοΈRoadmap
  • Introduction to the Stack
    • CMA, CSA, and ScandiPWA
    • Challenges
  • Setting up Scandi
    • Storefront Mode Setup
      • Proxying requests to server
    • Magento Mode Setup
    • Existing Magento 2 setup
    • Magento Commerce Cloud setup
    • Updating to new releases
      • Storefront mode upgrade
      • Magento mode upgrade
      • CMA upgrade
      • CSA upgrade
      • Custom ScandiPWA composer dependency update
      • Local ScandiPWA Composer Package Setup
    • Docker Setup [deprecated]
      • Legacy Docker setup
      • Migrating to CMA & CSA
  • Developing with Scandi
    • Override Mechanism
      • Overriding JavaScript
        • Overriding classes
        • Overriding non-classes
      • Overriding Styles
      • Overriding the HTML / PHP
      • Parent Themes
    • Extensions
      • Creating an extension
      • Installing an extension
      • Migrating from 3.x to 4.x
      • Publishing an extension
      • Extension Terminology
    • Working With Magento
      • Magento troubleshooting
      • Working with Magento modules
      • Working with GraphQL
      • GraphQL Security
      • Working with "granular cache"
    • Developer Tools
      • Debugging in VSCode
      • ScandiPWA CLI
      • Configuring ESLint
      • CSA Commands
    • Deploying Your App
      • Build & Deploy Android app
      • Build & Deploy iOS app
  • Structure
    • Directory Structure
    • Building Blocks
      • Components
        • Styling Components
      • Routes
      • Redux Stores
      • GraphQL Queries
      • Global Styles
      • The Util Directory
      • Type Checking
    • Application assets
    • Code Style
      • JavaScript Code Style
      • SCSS Code Style
  • Tutorials
    • Customizing Your Theme
      • Styling
        • Customizing the Global Styles
        • Adding a New Font
        • Overriding a Components Styles
        • Extending a Component's Styles
      • Customizing JavaScript
        • Customizing the Footer Copyright
        • Adding a New Page
        • Adding a Section in My Account
        • Adding a Tab on the Product Page
        • Creating a New Redux Store
    • Payment Method Integration
      • Setting Up for Development
      • Redirecting to the Payment Provider
      • Handling the Customer's Return
    • Creating a Custom Widget
      • Scandi CMS System Overview
      • Creating a Magento Widget
      • Implementing the Rendering
    • Video Tutorials
      • #1 Setting up and talking theory
      • #2 Templating in React
      • #3 Overriding a file
      • #4 Styling the application
      • #5 Patterns of ScandiPWA
    • Dark Mode Extension
    • Deploying Native Apps
    • Product 3D Model Extension
      • Part 1: Magento 3D Model Uploads
      • Part 2: GraphQL API
      • Part 3: Scandi Frontend
    • Social Share, Full Extension Development
      • STEP-1 and 2 Creating Magento 2 Module
      • STEP-3 Backend Configurations Settings
      • STEP-4 Simple GraphQl and Resolver
      • STEP-5 Creating Extension, Base Redux Store
      • STEP-6 Extension plugins
      • STEP-7 GraphQL types, Helpers
      • STEP-8 Query Field and FieldList
      • STEP-9 render Plugins and MSTP Plugin, Component creation
      • STEP-10 SocialShare Component Development
      • STEP-11 SocialShare for CategoryPage
      • TASK-1 Changing LinkedIn to Twitter
      • STEP-12 Comments for Admin Users
      • STEP-13 Final, bugfixes
    • Accessing Magento 2 Controllers
      • STEP-1 Creating Magento 2 Module
      • STEP-2 - Create Magento 2 Frontend Route and Basic Controller
      • STEP-3 Accessing Magento 2 Controller, Bypassing ScandiPWA frontend
      • STEP-4 Creating ScandiPWA Extension with additional dependencies
      • STEP-5 Creating Plugin and Axios request
  • About
    • Support
    • Release notes
    • Technical Information
    • Data Analytics
    • Contributing
      • Installation from Fork
      • Repository structure
      • Code contribution process
      • Submitting an Issue
      • Publishing ScandiPWA
Powered by GitBook
On this page
  • The Widget System
  • The Html Component
  • The WidgetFactory Component

Was this helpful?

  1. Tutorials
  2. Creating a Custom Widget

Scandi CMS System Overview

An overview of how the Scandi CMS system works with widgets.

First, let's get familiar with how the widget system works in Magento+Scandi. This will give you a high-level understanding on what bits of code need to be added to create a new widget.

Reading this section is optional, and only needed if you want to get a high-level understanding for the context of the code we'll be writing.

The Widget System

First, let's get familiar with how the widget system works in Magento+Scandi. As an example, suppose the Admin creates a home page CMS page with a RecentlyViewed widget. The CMS source code would contain a {{widget}} template:

<p>Some CMS text...</p>
<p>{{widget type="Magento\\Catalog\\Block\\Widget\\RecentlyViewed" uiComponent="widget_recently_viewed" page_size="5" show_attributes="name,image,price,learn_more" show_buttons="add_to_cart" template="product/widget/viewed/grid.phtml"}}</p>

When rendering the page, the Magento CMS system will parse the widget template, and convert it into a widget element:

<p>Some CMS text...</p>
<p>
    <widget type='RecentlyViewed' uiComponent='widget_recently_viewed' page_size='5'
            show_attributes='name,image,price,learn_more' show_buttons='add_to_cart'></widget>
</p>

On the frontend, Scandi will parse this element. Let's dive into the parsing logic.

The Html Component

In Scandi, the Html component is responsible for rendering all CMS content, including CMS pages and product descriptions. Instead of merely outputting the raw HTML, it parses its input. Then, some of the elements are replaced by React components. This means that CMS content can contain components just like any other part of the app!

Take a look at this simplified version of the HTML component:

node_modules/@scandipwa/scandipwa/src/component/Html/Html.component.js
import parser from 'html-react-parser';
import attributesToProps from 'html-react-parser/lib/attributes-to-props';
import domToReact from 'html-react-parser/lib/dom-to-react';
import PropTypes from 'prop-types';
import { PureComponent } from 'react';

import Image from 'Component/Image';
import Link from 'Component/Link';
import WidgetFactory from 'Component/WidgetFactory';
import { hash } from 'Util/Request/Hash';

/** @namespace Component/Html/Component */
export class Html extends PureComponent {
    static propTypes = {
        content: PropTypes.string.isRequired
    };

    rules = [
        {
            query: { name: ['widget'] },
            replace: this.replaceWidget
        },
        {
            query: { name: ['a'] },
            replace: this.replaceLinks
        },
        {
            query: { name: ['img'] },
            replace: this.replaceImages
        } // [...]
    ];

    parserOptions = {
        replace: (domNode) => {
            // [...] logic for replacing elements with components
        }
    };

    attributesToProps(attribs) {...}

    replaceLinks({ attribs, children }) {
        const { href, ...attrs } = attribs;

        return (
            <Link { ...attributesToProps({ ...attrs, to: href }) }>
                { domToReact(children, this.parserOptions) }
            </Link>
        );
    }

    replaceImages({ attribs }) {
        const attributes = attributesToProps(attribs);

        if (attribs.src) {
            return <Image { ...attributes } />;
        }
    }

    replaceWidget({ attribs }) {
        return <WidgetFactory { ...this.attributesToProps(attribs) } />;
    }

    render() {
        const { content } = this.props;
        return parser(content, this.parserOptions);
    }
}

Instead of rendering simple <a> anchor elements, the Html component replaces them with <Link> – making them work with the react-router. Instead of outputting <img> elements, it converts them into <Image> components, making them consistent with the rest of the app.

Importantly, all <widget> elements are turned into the <WidgetFactory> component. This is what enables Scandi to process the CMS widgets.

The WidgetFactory Component

In the WidgetFactory, different widget types are mapped to corresponding components. The renderContent function then renders the appropriate component for the widget, passing on all the attributes as props:

import PropTypes from 'prop-types';
import { lazy, PureComponent, Suspense } from 'react';

import RenderWhenVisible from 'Component/RenderWhenVisible';

import {
    CATALOG_PRODUCT_LIST,
    NEW_PRODUCTS,
    RECENTLY_VIEWED,
    SLIDER
} from './WidgetFactory.config';

import './WidgetFactory.style';

export const ProductListWidget = lazy(() => import(/* webpackMode: "lazy", webpackChunkName: "category" */ 'Component/ProductListWidget'));
export const NewProducts = lazy(() => import(/* webpackMode: "lazy", webpackChunkName: "category" */ 'Component/NewProducts'));
export const HomeSlider = lazy(() => import(/* webpackMode: "lazy", webpackChunkName: "cms" */ 'Component/SliderWidget'));
export const RecentlyViewedWidget = lazy(() => import(/* webpackMode: "lazy", webpackChunkName: "category" */ 'Component/RecentlyViewedWidget'));

/** @namespace Component/WidgetFactory/Component */
export class WidgetFactory extends PureComponent {
    static propTypes = {
        type: PropTypes.string.isRequired
    };

    renderMap = {
        [SLIDER]: {
            component: HomeSlider,
        },
        [NEW_PRODUCTS]: {
            component: NewProducts
        },
        [CATALOG_PRODUCT_LIST]: {
            component: ProductListWidget
        },
        [RECENTLY_VIEWED]: {
            component: RecentlyViewedWidget
        }
    };

    renderContent() {
        const { type } = this.props;
        const {
            component: Widget
        } = this.renderMap[type] || {};

        if (Widget !== undefined) {
            return (
                <RenderWhenVisible>
                    <Widget { ...this.props } />
                </RenderWhenVisible>
            );
        }

        return null;
    }

    render() {
        return (
            <Suspense fallback={ this.renderFallback() }>
                { this.renderContent() }
            </Suspense>
        );
    }
}

export default WidgetFactory;

Finally, the individual widget components (ProductListWidget, NewProducts, etc.) are regular React components responsible for rendering their widget.

PreviousCreating a Custom WidgetNextCreating a Magento Widget

Last updated 3 years ago

Was this helpful?