I trust that you found this blog post to be enjoyable. If you are interested in having my team handle your eCommerce setup and marketing for you, Contact Us Click here.

How can we add section using section rendering api in Shopify

How Can We Add section using section rendering API in Shopify | Shopify Online Store

Establishing a Shopify store lets you dynamically load items onto a page without having to reload the whole page. By raising the interactivity and responsiveness of your website, this tool is quite helpful for improving the user experience. Using JavaScript and Shopify's section rendering API, this article will guide you through the dynamically fetching and displaying of section content process.

Step 1: Create a Shopify Section

First, let's create a new section in Shopify with some dynamically loaded content. This example section displays a list of featured products.

  sections/featured-products.liquid

<div id="featured-products" class="featured-products">

  <h2> {{ section.settings.title }} </h2>

  <p> {{ section.settings.description }} </p>

  </div>


{% schema %}

{

  "name": "Featured Products",

  "settings": [

    {

      "type": "text",

      "id": "title",

      "label": "Title",

      "default": "Featured Products"

    },

    {

      "type": "textarea",

      "id": "description",

      "label": "Description",

      "default": "Check out our featured products."

    }

  ]

}

{% endschema %}

 

In this section you define the title, description and list of products to display. The section will be rendered with these settings.

Step 2: Update the Shopify Template

Next, we need to add this section in our Shopify template and add a button to trigger the dynamic loading of this section.

‘templates/index.json’

<!-- Button to load featured products -->

<button id="load-featured-products">Load Featured Products</button>

<!-- Container where the featured products will be loaded -->

<div id="main-content"></div>

 

 Here, we add a button with the ID load-featured-products and a container <div> with the ID main-content . This container is where the section content will be dynamically loaded.

 Step 3: Add JavaScript for Fetching and Displaying the Section

You need to add JavaScript to handle retrieving and rendering the section's content when the button is clicked. This script can be found in your theme's JavaScript file or in


<script>

  document.addEventListener('DOMContentLoaded', function() {

    // Define the fetchSection function

    function fetchSection(sectionId, containerId) {

      console.log(`Fetching section: ${sectionId} into container: ${containerId}`);

      fetch(`/sections?section_id=${sectionId}`)

        .then(response => {

          if (!response.ok) {

            throw new Error('Network response was not ok ' + response.statusText);

          }

          return response.text();

        })

        .then(html => {

          const parser = new DOMParser();

          const doc = parser.parseFromString(html, 'text/html');

          const newSection = doc.getElementById(sectionId);

          if (newSection) {

            const container = document.getElementById(containerId);

            console.log(`Fetched new section content: ${newSection.innerHTML}`);

            container.innerHTML = newSection.innerHTML;

          } else {

            console.error('No new section found with ID:', sectionId);

          }

        })

        .catch(error => console.error('Error fetching section:', error));

    }


    // Ensure the button event listener is defined within the same scope

    const loadButton = document.getElementById('load-featured-products');

    if (loadButton) {

      loadButton.addEventListener('click', function() {

        fetchSection('featured-products', 'main-content');

      });

    } else {

      console.error('Load button not found');

    }

  });

</script>

JavaScript Explained

  1. DOMContentLoaded Event: Guarantees that the script executes only after the entire DOM has been loaded.
  2. FetchSection Function: Utilises Shopify's Section Rendering API to retrieve the section HTML.
  3. DOM Parsing: Replaces the existing content in the target container by parsing the retrieved HTML.
  4. Event Listener: Affixes an event listener to the button to initiate the section update upon activation.

Debugging Steps

  1. Console Logs: Use the browser's developer console to check logs and any error messages.
  2. Network Request: Verify that the fetch request is made correctly and check the response.
  3. DOM Parsing: Ensure the fetched HTML contains the section with the correct ID.
  4. Button Existence: Ensure the button exists in the DOM before trying to add an event listener.

Conclusion:

JavaScript and the section rendering API will enable you to dynamically import and display content in your Shopify store by adhering to these procedures. This method enhances the user experience by preventing the need for entire page reloads and enhancing the interactivity of your website.

 

Back to blog