> For the complete documentation index, see [llms.txt](https://docs.scandipwa.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.scandipwa.com/tutorials/product-3d-model-extension/part-3-scandi-frontend.md).

# Part 3: Scandi Frontend

## Prerequisites

Before you start with this section, you need to have a [Scandi theme set up](https://docs.scandipwa.com/getting-started/getting-started/storefront-mode) and [linked to your Magento instance](https://docs.create-magento-app.com/usage-guide/themes#2-linking-a-theme).

## Creating a Scandi Extension

We already have a backend module for our extension, but we need a separate Scandi extension Javascript module, responsible for implementing the frontend functionality. An extension is a reusable package that can be installed on any Scandi theme.

To create an extension, navigate to the root of your CSA application in the terminal. You can [create a new extension](https://docs.scandipwa.com/stack/extensions/creating-an-extension) using the `scandipwa` script:

```bash
scandipwa extension create 
```

{% hint style="info" %}
If you haven't installed the [Scandi CLI script](https://docs.scandipwa.com/dev-environment/scandipwa-cli), you can do so with `npm i -g scandipwa-cli`. It will automate certain tasks, making development faster.
{% endhint %}

This script will initialize a new extension named `packages/product-3d-scandi` and configure your theme to install it. It will also enable it by setting `scandipwa.extensions["product-3d-scandi"]` to `true` in `package.json`.

## Updating the Product Query

We have an API available to get the 3D models for each product. However, due to the design of GraphQL, this data won't be fetched unless the query specifically requests it (this helps save bandwidth on unused fields). Hence, the first step is to update the query so that 3D models are requested as well.

Unlike many other applications, Scandi builds queries at runtime, using its [GraphQL library](https://docs.scandipwa.com/structure/building-blocks-summary/constructing-graphql-queries#generating-graphql-queries). This means that updating the query for the purposes of an extension is as easy as [creating a plugin](https://docs.create-scandipwa-app.com/extensions/application-plugins).

The `ProductList` query creator is responsible for making product queries. In particular, we are interested in the `_getProductInterfaceFields` method, which is responsible for specifying the product fields we want to query.

{% hint style="info" %}
If need to plug into a query creator, but don't know its class, you can inspect the related source code to see which query it uses.
{% endhint %}

The current implementation of `_getProductInterfaceFields` already returns multiple fields, represented as an array of strings:

```javascript
[
  "id",
  "sku",
  "name",
  "type_id",
  "stock_status",
  // [...]
]
```

{% hint style="info" %}
More complex fields that also have sub-fields can be represented by an instance of the `Field` class. This will not be necessary for our purposes.
{% endhint %}

We want to wrap around this method, get the "original" array, and return an array with a new field, `"model_3d_urls"`, in addition to the original ones:

{% code title="src/plugin/ProductList.query.plugin.js" %}

```javascript
export const _getProductInterfaceFields = (args, callback, instance) => {
  const originalFields = callback(...args);
  return [...originalFields, "model_3d_urls"];
};

export default {
  "Query/ProductList": {
    "member-function": { _getProductInterfaceFields },
  },
};
```

{% endcode %}

{% hint style="info" %}
The plugin mechanism will wrap the `_getProductInterfaceFields` method of the `ProductList` query with our custom plugin – whenever `_getProductInterfaceFields`is called, our plugin will be used instead.

The original arguments will be provided in the `args` parameter, and the original function will be given in `callback` (`instance` is the class instance the method was called on, but we don't need it in this example).

We get the original fields returned by the function by calling the original function with the provided arguments (line 3). If this still seems confusing, feel free to refer to the [plugin documentation](https://docs.create-scandipwa-app.com/extensions/application-plugins).
{% endhint %}

{% hint style="success" %}
If you restart your app and open the Product Detail Page, you can verify in your browser's network tab that the `model_3d_urls` are indeed returned in the product request.
{% endhint %}

## Creating a 3D Model Component

We want to be able to display a carousel of 3D models on the product page, but we don't have any components with this functionality – so we need to create a new one. Again, we can use the CLI tool instead of creating the boilerplate manually

```
scandipwa create component Product3DViewer
```

Expected output:

```
     The following files have been created:
     src/component/Product3DViewer/Product3DViewer.component.js
     src/component/Product3DViewer/Product3DViewer.style.scss
     src/component/Product3DViewer/index.js
```

## Rendering a Product Tab

Now that we have a placeholder component, let's render it on the product page – we want it to appear in one of the tabs below the product image:

![](/files/-M_0Rqd5-4Qn3GiLgh2Q)

We can do this with a plugin, but first we need to find the function we need to plug in to. To do this, we can inspect the source code for the `ProductPage` component.

{% hint style="info" %}
How did I know to check the ProductPage component? I used the React developer tools to determine the name of the component, then found it in the source code directory. It's a good idea to install these[ developer extensions](broken://pages/-MOVDCW03Ud-lKz1G5Il#browser-plugins) to make such tasks easier.
{% endhint %}

After looking through the source code, it becomes clear that we need to focus on the `tabMap` property:

{% code title="Scandi base code: route/ProductPage/ProductPage.component.js" %}

```jsx
// [...]

/** @namespace Route/ProductPage/Component */
export class ProductPage extends PureComponent {
// [...]

    tabMap = {
        [PRODUCT_INFORMATION]: {
            name: __('About'),
            shouldTabRender: () => {
                const { isInformationTabEmpty } = this.props;
                return isInformationTabEmpty;
            },
            render: (key) => this.renderProductInformationTab(key)
        },
        [PRODUCT_ATTRIBUTES]: {
            name: __('Details'),
            shouldTabRender: () => {
                const { isAttributesTabEmpty } = this.props;
                return isAttributesTabEmpty;
            },
            render: (key) => this.renderProductAttributesTab(key)
        },
        [PRODUCT_REVIEWS]: {
            name: __('Reviews'),
            // Return false since it always returns 'Add review' button
            shouldTabRender: () => false,
            render: (key) => this.renderProductReviewsTab(key)
        }
    };
    
// [...]
}

export default ProductPage;
```

{% endcode %}

This -map pattern is fairly common in Scandi. It works by defining an object of similar, but distinct renderable elements. Then, a render function takes this data and renders it in the appropriate place.

This extra step of defining an object might seem counter-intuitive, but it will actually be quite helpful for our purposes. Now, to add a tab, all we have to do is add an entry to this `tabMap` field. This is easy to do with a member property plugin:

```jsx
import Product3DViewer
  from "../component/Product3DViewer/Product3DViewer.component";

export const PRODUCT_3D_MODEL_TAB = "PRODUCT_3D_MODEL_TAB";

export const render3dModelTab = (key, modelUrls) => {
  return (
    <Product3DViewer key={key} modelUrls={modelUrls}/>
  );
};

// a member plugin takes the original member value
// and returns the new value that the member should have
export const tabMap = (member, instance) => {
  return {
    ...member,
    [PRODUCT_3D_MODEL_TAB]: {
      name: __("3D Models"),
      shouldTabRender: () => {
        const { product: { model_3d_urls = [] } = {} } = instance.props;
        console.log(instance.props);

        // For some reason, shouldTabRender needs to return the opposite
        // of what you would think
        return !(model_3d_urls.length > 0);
      },
      render: (key) => {
        const { product: { model_3d_urls = [] } = {} } = instance.props;

        return render3dModelTab(key, model_3d_urls);
      },
    },
  };
};

export default {
  "Route/ProductPage/Component": {
    "member-property": { tabMap },
  },
};
```

{% hint style="info" %}
You might have noticed we used a function called `__`. Its job is to translate strings to the appropriate locale in production builds. It is a good practice to always wrap text visible to the user in `__("")`, in case you want to add translations later.
{% endhint %}

## Implementing 3D Rendering

Now we need to implement the main functionality – 3D model rendering. Since this is quite a complex feature, we will make use of a library to do all the heavy lifting for us. I considered implementing the viewer in [Three.js](https://threejs.org/), which has bindings for use in React. However, I found that there is a library that makes things even easier. The [model-viewer](https://modelviewer.dev/) library not only displays a 3D model, but also provides mouse interaction functionality and automatic rotation out-of-the-box.

It also integrates seamlessly with React – all we have to do to use it is to render a `<model-viewer>` element (this is not technically a React component, but we can still treat it like any other element).

First, we need to load the library. For some reason, installing it via `npm` and importing it as a module did not work – most likely, there is some conflict between the Webpack configuration in Scandi and model-viewer's module format. To work around this, we can load the module with a CDN:

{% code title="src/component/Product3DViewer/Product3DViewer.component.js" %}

```jsx
function loadModelViewer() {
  const MODULE_URL =
    "https://unpkg.com/@google/model-viewer/dist/model-viewer.min.js";

  const script = document.createElement("script");
  script.src = MODULE_URL;
  script.type = "module";

  document.head.appendChild(script);
}

loadModelViewer();
```

{% endcode %}

Now we can render a 3D model in our Product3DViewer component:

```jsx
  render() {
    const { modelUrls } = this.props;

    const url = modelUrls[0];

    return (
      <div block="Product3DViewer">
        <model-viewer
          class="Product3DViewer-Model"
          src={url}
          alt={__("Product 3D Model")}
          auto-rotate
          camera-controls
        ></model-viewer>
      </div>
    );
  }
```

The only functionality left to implement is pagination between different models – as the admin might have uploaded more than one, but currently only the first one is shown. To implement this pagination, we need to store the currently active model index in the state:

```javascript
  state = {
    // Keep track of the currently visible model
    activeModelIndex: 0,
  };
```

Now, we can use `modelUrls[activeModelIndex]` to get the current model. By updating the state, we can change which model is active: `setState({ activeModelIndex: activeModelIndex + 1 })`, so let's implement a switcher enabling the user to navigate between different models:

```jsx
renderModelSwitcher() {
    const { modelUrls } = this.props;
    const { activeModelIndex } = this.state;

    // activeModelIndex is 0-indexed, but 1-indexed pages make more sense
    // so we add 1 to display it to the user
    const activeNumber = activeModelIndex + 1;
    
    const size = modelUrls.length;

    // We'll want to disable the "Previous" button for the first model
    // and the "Next" button for the last model
    const isFirst = activeModelIndex <= 0;
    const isLast = activeModelIndex >= size - 1;

    // Render no switcher if there is only one model
    if (size < 2) {
      return null;
    }

    return (
      <div block="Product3DViewer" elem="Switcher">
        <button
          block="Product3DViewer"
          elem="Button"
          disabled={isFirst}
          onClick={() =>
            this.setState({ activeModelIndex: activeModelIndex - 1 })
          }
        >
          {__("Previous")}
        </button>
        <span block="Product3DViewer" elem="ActiveIndex">
          {activeNumber}
        </span>
        <button
          block="Product3DViewer"
          elem="Button"
          disabled={isLast}
          onClick={() =>
            this.setState({ activeModelIndex: activeModelIndex + 1 })
          }
        >
          {__("Next")}
        </button>
      </div>
    );
  }
```

Whenever the user clicks a button that updates the state, the active model index is changed, and the component is re-rendered with the new model. When we put this all together, we get a component that can display a carousel of 3D models:

{% code title="src/component/Product3DViewer/Product3DViewer.component.js" %}

```jsx
import PropTypes from "prop-types";
import { PureComponent } from "react";

import "./Product3DViewer.style";

export class Product3DViewer extends PureComponent {
  // Define the props that this component expects to receive
  // Checked at runtime in development builds
  static propTypes = {
    modelUrls: PropTypes.arrayOf(PropTypes.string),
  };

  state = {
    activeModelIndex: 0,
  };

  renderModelSwitcher() {
    const { modelUrls } = this.props;
    const { activeModelIndex } = this.state;

    const activeNumber = activeModelIndex + 1;
    const size = modelUrls.length;

    const isFirst = activeModelIndex <= 0;
    const isLast = activeModelIndex >= size - 1;

    if (size < 2) {
      return null;
    }

    return (
      <div block="Product3DViewer" elem="Switcher">
        <button
          block="Product3DViewer"
          elem="Button"
          disabled={isFirst}
          onClick={() =>
            this.setState({ activeModelIndex: activeModelIndex - 1 })
          }
        >
          {__("Previous")}
        </button>
        <span block="Product3DViewer" elem="ActiveIndex">
          {activeNumber}
        </span>
        <button
          block="Product3DViewer"
          elem="Button"
          disabled={isLast}
          onClick={() =>
            this.setState({ activeModelIndex: activeModelIndex + 1 })
          }
        >
          {__("Next")}
        </button>
      </div>
    );
  }

  render() {
    const { modelUrls } = this.props;
    const { activeModelIndex } = this.state;

    const url = modelUrls[activeModelIndex];

    return (
      <div block="Product3DViewer">
        {this.renderModelSwitcher()}
        <model-viewer
          class="Product3DViewer-Model"
          src={url}
          alt={__("Product 3D Model")}
          auto-rotate
          camera-controls
        ></model-viewer>
      </div>
    );
  }
}

export default Product3DViewer;
```

{% endcode %}

{% hint style="info" %}
If you are new to React, this might seem a bit overwhelming. The [React tutorials](https://reactjs.org/tutorial/tutorial.html#what-is-react) are a great place to learn the basics of React.
{% endhint %}

![3D models on the product page!!](/files/-M_521HBer5aLXxQcCkU)

3D Models used in the example above: "[National Park Binoculars - Hand Painted](https://sketchfab.com/3d-models/national-park-binoculars-hand-painted-37075392da5c410ab6944dcd42359a3d)" by [Adam Tabone](https://sketchfab.com/Adamoo) and "[Low poly McCree](https://sketchfab.com/3d-models/low-poly-mccree-38aedc02c0b2412babdc4d0eac7c6803)" by [Seafoam](https://sketchfab.com/seafoam)

## What Next?

Congratulations, now you have learned how to implement completely new functionality in Scandi, from the Magento backend all the way to the Scandi React frontend. We can't wait to see what you'll create with this knowledge!

By the way, you can find the [final code created in this tutorial on Gitlab](https://gitlab.com/scandi-tutorials/product-3d-models).

*Written by Reinis Mazeiks. Feel free to ask questions and share feedback in the* [*Slack channel*](https://scandipwa.slack.com/archives/C01STHKG5RQ)*. Thanks for reading!*


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.scandipwa.com/tutorials/product-3d-model-extension/part-3-scandi-frontend.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
