Image Process - 2. Show images in react datatable from API, Step by Step

 In this tutorial, we will learn to show images in Datatable. We will fetch image data from API as JSON and then load it in Datatable.
Here we have used react 'react-data-table-component' library. See here how to set up this library to execute a single command.

Show Image screenshot

Step 1. Firstly, we will collect JSON data from API. In number [1], we called a function to get data from API.

Code breakdown

Sample JSON - 
[
  {
    "menuID": "100103",
    "menuName": "Chocolate Coffee",
    "photoID": "img_100101",
    "photoFile": "/9j/4AAQSkZJRgABAQAAAQABAAD/"
  }
]

Step 2: In number [2], we mapped the JSON field name in the selector Row. Here, we have used <img> tag to show the image in the Photo column. 

<img src={'data:image/png;base64,' + row.photoFile} /> 

Here 'data:image/png;base64,' is a common string as a prefix. And row.photoFile is the main image base64 data fetched from API.

Step 3: Finally columns and data are added to the Data table.
columns={columns}
data={data}

Done 👍

Code 👇

Component
import { Toast } from "../Toast";
import React, { useEffect, useState } from "react";
import MenuCategoryController from '../../controllers/MenuCategoryController';
import DataTable from 'react-data-table-component';

function MenuHomePage() {
    const [data, setData] = useState([]);
    const controller = new MenuCategoryController();
    useEffect(() => {
        controller.getAllMenu(
            (data) => {
                setData(data);
                console.log("Data : ", JSON.stringify(data))
            },
            (errorMessage) => { Toast(errorMessage, 'error'); }
        );
    }, []);
    const columns = [
        {
            name: 'Name',
            selector: row => row.menuName,
        },
        {
            name: 'Photo',
            cell: row => <img src={'data:image/png;base64,' + row.photoFile} alt="Menu" style={{ width: '80px', height: '80px' }} />,
        }
    ];
    return (
        <div className='container'>
            <DataTable
                columns={columns}
                data={data}
                pagination
                paginationPerPage={5}
                paginationRowsPerPageOptions={[10, 15, 20, 25, 30]}
                fixedHeader
                pointerOnHover
                striped
            ></DataTable>
        </div>
    )
}
export default MenuHomePage;


Controller Function 
    async getAllMenu(onSuccess, onError) {
        try {
            const data = await getData('http://localhost:8080/v1/menus'); // Set URL here
            onSuccess(data);
        } catch (e) {
            console.log("Controller, Error : " + e);
            onError(e);
        }
    };

API Service
export const getData = async(url)=>{
  try {
    const response = await axios.get(url);
    return response.data.results;
  } catch (error) {
    throw new Error('Error fetching data:', error);
  }
};



Post a Comment

0 Comments