How to Show Image in Salesforce LWC Data Table? : Bijay Kumar

How to Show Image in Salesforce LWC Data Table?
by: Bijay Kumar
blow post content copied from  SalesForce FAQs
click here to view original post



### Summary of Content In Salesforce Lightning Web Components (LWC), displaying images in data tables requires creating a custom data type since there is no default type for images. This tutorial explains two methods to show images in LWC data tables: 1. **Using a Third-Party API**: You can fetch product data, including images, from an external API and display it in a data table. 2. **Using Apex**: You can retrieve images stored in a custom URL field from Salesforce objects (like Opportunity) and display them in the data table. ### Key Steps for Each Method #### Method 1: Displaying Images via Third-Party API 1. **Create a Custom Data Type**: Extend the Lightning data table to include a custom type for images. 2. **Fetch Data**: Use the Fetch API to get product data from an external source (e.g., `fakestoreapi.com`). 3. **Set Up Trusted URLs**: Add the API domain to Salesforce's trusted URLs. 4. **Define Columns**: Create a column configuration that includes the custom image type. 5. **Render Images**: Use a custom HTML template to display images in the data table. #### Method 2: Displaying Images via Apex 1. **Create an Apex Controller**: Write a controller to fetch Opportunity records with image URLs. 2. **Set Up LWC Component**: Create an LWC component that uses the Apex method to get data. 3. **Define Columns**: Similar to the first method, define columns including the custom image type. 4. **Render Images**: Use a separate HTML template for displaying images. ### Conclusion This tutorial provides a comprehensive guide on how to display images in Salesforce LWC data tables using both third-party APIs and Apex methods. By following the outlined steps, developers can enhance their applications with visual data representation. ### Additional Context - **Salesforce LWC**: A framework for building user interfaces in Salesforce, allowing developers to create reusable components. - **Apex**: A strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the Salesforce platform. ### Hashtags for SEO #Salesforce #LWC #LightningWebComponents #DataTable #Apex #APIIntegration #WebDevelopment #SalesforceTutorial #CustomDataTypes #ImageDisplay #SalesforceDevelopment #FrontendDevelopment #SalesforceCommunity


In Salesforce LWC data tables, when we display data, then we use the type parameter to define the data type of the column field. For example, to display currency field we will use type:currency. In the LWC lightning data table, we don’t have a default type to display image in the data table column.

We need to define a custom data type to display an image in the data table. In this Salesforce tutorial, we will learn how to show an image in Salesforce LWC data table.

Show Images in Salesforce LWC Data Table Column

To display the image in a LWC table column, we have two options: either we can make a callout in the LWC component from an open source API, or another method is via calling the Apex method to display the images of a specific object in the data table.

In the below example, we will display the image column in the LWC data table for the following methods.

  • Show Images in Salesforce LWC Data Table Column via API calling from an external third-party open-source
  • Show Images in Salesforce LWC Data Table Column via Apex calling for internal objects.

Show Images in Salesforce LWC Data Table Column via Third-party API Calling

In the below example, we will create a LWC component with an extended Lightning datatable class, in which we will define a static property of custom type for the image column.

In the below example, I will fetch a product list from the API and show it in the LWC data table. To get the data in the table, we can use the Apex class callout or the fetch API method to call the third-party API.

In this example, I’m using Open API to get a list of products along with images.

To make the API call directly in the LWC component, we need to add the API domain to the trusted URLs. After this, follow the steps below

To enter a site on trusted URLs, navigate to the Setup> Trusted URLs > Enter the API Name and URL > mark it as active and click Save.

How to display image column in LWC data table

After setting up the trusted URL for third party API, follow the steps below to display the image from the fetched API in the data table.

1. Create an LWC component with extended lightning data table and define the column array as shown in the code below.

import { LightningElement } from 'lwc';

const COLUMNS = [
    { label: 'Title', fieldName: 'title' },
    { label: 'Description', fieldName: 'description' },
    { label: 'Price', fieldName: 'price', type: 'currency' },
    { label: 'Image', fieldName: 'image', type: 'customImage' }
];

export default class ProductList extends LightningElement {
    columns = COLUMNS;
    products = [];

    connectedCallback() {
        this.getProducts();
    }

    async getProducts() {
        const response = await fetch('https://fakestoreapi.com/products');
        if (response.ok) {
            this.products = await response.json();
        }
    }
}

2. Enter the below code in the HTML to render the product fetched from the open API.

<template>
    <lightning-card title="Products" icon-name="standard:product">
        <div class="slds-var-p-around_medium">
            <c-enhanced-data-table key-field="id" data={products} columns={columns} hide-checkbox-column="true"></c-enhanced-data-table>
        </div>
    </lightning-card>
</template>

The <c-enhanced-data-table …></c-enhanced-data-table> tag uses the enhancedDataTable component, configured with key-field=”id” to set the row identifier, data={products} to bind the product data, columns={columns} to define the table columns.

It embeds the custom datatable in a card, passing data and settings to display products.

3. Enter the below code in the meta.xml file to make the component visible to the lightning pages.

<isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>

4. Create another LWC component and enter the below code in the JS file.

This component will inherit the lightning table class, and here we can do customization for the data table.

import LightningDatatable from 'lightning/datatable';
import customImage from './customImage.html';

export default class EnhancedDataTable extends LightningDatatable {
    static customTypes = {
        customImage: {
            template: customImage,
            typeAttributes: ['title']
        }
    };
}

In the above code, we have a static property customTypes that registers a custom column type called customImage for the datatable.

In this section, we customize the datatable with static customTypes = { customImage: { template: customImage, typeAttributes: [‘title’] } };. The static customTypes property defines a new column type called customImage.

It uses template: customImage to link to the imported customImage.html file for rendering an image and typeAttributes: [‘title’], which enables the data table to display a customImage column for images.

5. In the second LWC component, I have created another HTML file to display the product image in the data table.

<template>
    <img src={value} title={typeAttributes.title} 
    class="slds-avatar slds-avatar_circle slds-avatar_large"
    alt="Product Image" />
</template>

This template will render an <img> in the customImage column, with src={value} setting the image URL, title={typeAttributes.title} adding a tooltip, SLDS classes (slds-avatar slds-avatar_circle slds-avatar_large) styling it as a large image.

6. Now, deploy the LWC component to the Lightning page and there you will see that using the fetched API data we have displayed product records along with images.

Display image in Salesforce LWC data table

This way, we can display the image column in Salesforce LWC data table via third-party API calling and using an open-source API.

Show Images in Salesforce LWC Data Table Column via Apex calling

In this method, we will display an image on the LWC data table via the Apex calling. In this example, I have a custom URL field Item_Image__c in the Opportunity object.

The URL field contains the image URL link from the external link, and in the LWC data table, we will display the images fetched from the URL.

Follow the steps below to display images in LWC data table via apex calling method.

1. Create a controller class to fetch the records from the opportunity object and the custom image URL field.

public with sharing class OpportunityController {
    @AuraEnabled(cacheable=true)
    public static List<Opportunity> getOpportunityList() {
        return [SELECT Id, Name, Amount, StageName, Item_Image__c 
                FROM Opportunity 
                WHERE Item_Image__c != NULL 
                LIMIT 10];
    }
}

In the controller class, we have added the condition Item_Image__c != NULL to ensure that the table shows only records with images.

2. Create an LWC component and enter the below code in the JS class.

import { LightningElement, wire } from 'lwc';
import getOpportunityList from '@salesforce/apex/OpportunityController.getOpportunityList';

const COLUMNS = [
    { label: 'Opportunity Name', fieldName: 'Name' },
    { label: 'Amount', fieldName: 'Amount', type: 'currency' },
    { label: 'Stage', fieldName: 'StageName' },
    { label: 'Item Image', fieldName: 'Item_Image__c', type: 'customImage', typeAttributes: { class: 'slds-avatar_large' } }
];

export default class OpportunityList extends LightningElement {
    columns = COLUMNS;
    opportunities = [];

    connectedCallback() {
        console.log('Columns initialized:', JSON.stringify(this.columns));
    }

    @wire(getOpportunityList)
    wiredOpportunities({ error, data }) {
        if (data) {
            console.log('Opportunities data:', JSON.stringify(data));
            this.opportunities = data;
        } else if (error) {
            console.error('Error fetching opportunities:', error);
        }
    }
}

This main LWC component sets up a table with columns for the opportunity fields, including images. The Item_Image__c column uses a special type called customImage to show pictures.

The CSS styling typeAttributes: { class: ‘slds-avatar_large’ } will make the image icons big for better visibility in the data table.

We have called the Apex method to get the Opportunity data and store it in the data table.

3. After this, enter the below code in the HTML file.

<template>
    <lightning-card title="Opportunities with Product image">
        <div class="slds-var-p-around_medium">
            <c-enhanced-data-table 
                     key-field="Id" 
                     data={opportunities} 
                     columns={columns} 
            hide-checkbox-column="true">
        </c-enhanced-data-table>
        </div>
    </lightning-card>
</template>

This HTML template uses the <c-enhanced-data-table> tag, which uses another component we’ll make to show the table. It uses opportunities for the data, columns for the table setup, and ID to identify each row.

4. Create another LWC componentenhancedDataTable, and enter the code below in the JS file. This component will be the helper component that displays images in the first LWC component data table.

import LightningDatatable from 'lightning/datatable';
import customImage from './customImage.html';

export default class EnhancedDataTable extends LightningDatatable {
    static customTypes = {
        customImage: {
            template: customImage,
            typeAttributes: ['title', 'class']
        }
    };
}

In this code, we have added a new type to display an image that is customImage. This type uses a separate HTML file (customImage.html) to show the image in a table. The typeAttributes allow us to add extra details like a title or style.

5. Create an HTML template customImage.html in the same LWC component to define the logic of rendering image in the LWC data table.

<template>
    <img src={value} title={typeAttributes.title} class={typeAttributes.class} alt="Item Image" />
</template>

This template uses src={values} to get the URL from Item_Image__c and display the image.

6. Enter the code below in the meta.xml file where you have called the apex method to make the component available for the lightning pages.

<isExposed>true</isExposed>

    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>

7. Deploy the LWC component on the Lighting page and there you will see the LWC data table with images of respective records in the Item Image column.

Display Image column in Salesforce LWC data table

This way, we can display the image column in Salesforce LWC data tables via apex calling method and using the URL image fields.

Conclusion

In this Salesforce tutorial, we have learned how to add an image column to a Salesforce LWC data table by following the above method. We have also learned about two methods for displaying images in the LWC data table, where we displayed images using the third-party open API by using the fetch API method and a helper component.

After this, we displayed images from the custom URL field of the opportunity object, where we fetched the records via apex calling method.

You may also like to read:

The post How to Show Image in Salesforce LWC Data Table? appeared first on SalesForce FAQs.


March 03, 2025 at 09:48AM
Click here for more details...

=============================
The original post is available in SalesForce FAQs by Bijay Kumar
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce