Display Products in a Shopify App with Remix.js and Polaris | Shopify App Development

In the world of eCommerce, effectively displaying products is key to providing a great shopping experience. Shopify, one of the most popular eCommerce platforms, allows developers to create custom apps that can enhance the functionality of a store, including how products are presented to users. In this article, we will walk through the process of building a Shopify app that displays products using Remix.js and Shopify Polaris. By following this step-by-step guide, you will learn how to leverage modern web development tools to create a seamless, user-friendly product display in a custom Shopify app.

Why Use Remix.js and Polaris for Shopify App Development?

Before diving into the technical steps, it’s important to understand why Remix.js and Shopify Polaris are the tools of choice for developing Shopify apps:

  • Remix.js: Remix is a full-stack React framework that excels in server-side rendering (SSR) and optimized data loading. It provides a robust structure for building fast, scalable, and SEO-friendly applications, making it ideal for dynamic eCommerce platforms like Shopify.
  • Shopify Polaris: Polaris is Shopify’s design system that offers a comprehensive set of React components designed to maintain consistency with Shopify’s admin interface. Using Polaris ensures that your app’s user interface aligns with Shopify’s design standards, providing a seamless experience for users.

Setting Up Your Development Environment

To start building your Shopify app, you need to set up your development environment. Follow these steps to get started:

  1. Install Node.js: Ensure that Node.js and npm (Node Package Manager) are installed on your machine.
  2. Create a Shopify App with Remix.js: Use the Shopify CLI to create a new app with Remix.js as the frontend framework:bashCopy codeshopify app create node -t remix This command initializes a new Shopify app using Remix.js, providing the foundation for our product display functionality.
  3. Install Shopify Polaris: Navigate to your app’s directory and install Polaris components:bashCopy codenpm install @shopify/polaris
  4. Set Up Remix.js: Ensure that your Remix.js environment is properly configured, including setting up routes, loaders, and actions to handle data fetching and user interactions.

Fetching Product Data from Shopify API

To display products in your Shopify app, the first step is to fetch the relevant product data from the Shopify API.

Step 1: Configure Shopify API Access

Make sure your Shopify app is configured to access the Shopify API. In your shopify.config.js file, include the necessary API credentials:

javascriptCopy codemodule.exports = {
  apiKey: process.env.SHOPIFY_API_KEY,
  apiSecretKey: process.env.SHOPIFY_API_SECRET,
  scopes: ['read_products'],
  shop: process.env.SHOPIFY_SHOP,
  accessToken: process.env.SHOPIFY_ACCESS_TOKEN,
};

Store your API key and access token securely in environment variables.

Step 2: Create a Function to Fetch Products

Next, create a utility function to fetch the list of products from the Shopify API. In your utils directory, create a file named fetchProducts.js:

javascriptCopy codeimport { gql } from 'graphql-request';
import { shopifyClient } from './shopifyClient';

export async function fetchProducts() {
  const query = gql`
    {
      products(first: 20) {
        edges {
          node {
            id
            title
            handle
            descriptionHtml
            priceRange {
              minVariantPrice {
                amount
              }
            }
            images(first: 1) {
              edges {
                node {
                  src
                }
              }
            }
          }
        }
      }
    }
  `;

  const response = await shopifyClient.request(query);
  return response.products.edges.map(edge => edge.node);
}

This function sends a GraphQL query to Shopify’s API to retrieve details about the first 20 products, including their title, description, price, and image.

Displaying Products Using Polaris Components

With the product data fetched, the next step is to display it using Polaris components in a user-friendly format.

Step 1: Create the Products Page

Create a new component, ProductsPage.jsx, in your components or pages directory. This component will display the products in a grid or list format using Polaris components:

javascriptCopy codeimport { Page, Card, Layout, TextContainer, Heading, Image, TextStyle } from '@shopify/polaris';
import { useLoaderData } from '@remix-run/react';
import { fetchProducts } from '../utils/fetchProducts';

export async function loader() {
  const products = await fetchProducts();
  return products;
}

function ProductsPage() {
  const products = useLoaderData();

  return (
    <Page title="Products">
      <Layout>
        {products.map(product => (
          <Layout.Section key={product.id} oneHalf>
            <Card title={product.title} sectioned>
              <Image
                source={product.images.edges[0]?.node.src || 'https://via.placeholder.com/150'}
                alt={product.title}
              />
              <TextContainer>
                <Heading element="h4">{product.title}</Heading>
                <TextStyle variation="subdued">
                  ${parseFloat(product.priceRange.minVariantPrice.amount).toFixed(2)}
                </TextStyle>
                <div dangerouslySetInnerHTML={{ __html: product.descriptionHtml }} />
              </TextContainer>
            </Card>
          </Layout.Section>
        ))}
      </Layout>
    </Page>
  );
}

export default ProductsPage;

In this code:

  • Page Component: The Page component structures the content, providing a consistent layout with a title and other elements.
  • Layout and Layout.Section: These components help organize the page into a grid format, making it easy to display products in an organized manner.
  • Card Component: Each product is displayed within a Card, which provides a clean and professional look.
  • Image Component: The Image component displays the product image, with a fallback placeholder if no image is available.
  • TextContainer and Heading Components: These components organize and style the product title, description, and price.

Enhancing the Product Display

To create a more robust and user-friendly product display, consider adding the following features:

  1. Search and Filters: Implement search functionality and filters (e.g., by price, category, or availability) to help users find specific products more easily.
  2. Pagination: If you have a large number of products, implement pagination to allow users to navigate through pages of product listings.
  3. Product Sorting: Allow users to sort products by different criteria, such as price, popularity, or date added.

Here’s an example of adding search functionality:

javascriptCopy codeimport { useState } from 'react';
import { Page, Card, Layout, TextContainer, Heading, Image, TextStyle, TextField } from '@shopify/polaris';

function ProductsPage() {
  const products = useLoaderData();
  const [searchTerm, setSearchTerm] = useState('');

  const filteredProducts = products.filter(product =>
    product.title.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <Page title="Products">
      <TextField
        label="Search Products"
        value={searchTerm}
        onChange={(value) => setSearchTerm(value)}
        clearButton
        onClearButtonClick={() => setSearchTerm('')}
      />
      <Layout>
        {filteredProducts.map(product => (
          <Layout.Section key={product.id} oneHalf>
            <Card title={product.title} sectioned>
              <Image
                source={product.images.edges[0]?.node.src || 'https://via.placeholder.com/150'}
                alt={product.title}
              />
              <TextContainer>
                <Heading element="h4">{product.title}</Heading>
                <TextStyle variation="subdued">
                  ${parseFloat(product.priceRange.minVariantPrice.amount).toFixed(2)}
                </TextStyle>
                <div dangerouslySetInnerHTML={{ __html: product.descriptionHtml }} />
              </TextContainer>
            </Card>
          </Layout.Section>
        ))}
      </Layout>
    </Page>
  );
}

export default ProductsPage;

Testing and Deployment

After implementing the product display functionality, thoroughly test your app to ensure it works correctly:

  • Data Accuracy: Verify that all product details are fetched and displayed correctly.
  • User Experience: Ensure that the UI is responsive and intuitive, providing clear feedback to users.
  • Performance: Check that the app performs well, even with a large number of products, and that loading times are optimized.

Once testing is complete, deploy your Shopify app using the Shopify CLI:

bashCopy codeshopify app deploy

Conclusion

Displaying products in a custom Shopify app using Remix.js and Polaris is an essential feature that enhances the shopping experience for users. By following this tutorial, you’ve learned how to fetch product data from the Shopify API, display it using Polaris components, and enhance the display with features like search and filtering.

As you continue to develop Shopify apps, mastering these tools will enable you to create high-quality, custom solutions that meet the needs of Shopify merchants. Whether you’re building a simple product catalog or a complex eCommerce solution, the combination of Remix.js and Polaris offers the flexibility and scalability needed to create a seamless, user-friendly experience.

Leave a Reply

Your email address will not be published. Required fields are marked *