DEV Community

Cover image for How To Fetch Image From Database and Display In React JS
Udemezue John
Udemezue John

Posted on

2

How To Fetch Image From Database and Display In React JS

Introduction.

Fetching an image from a database and showing it in a React JS app might sound like a tricky task at first glance, but it isn’t.

I want to share my insights on this topic in a friendly, step-by-step way that makes the whole process feel natural and manageable.

In this article, I will explain why this topic matters, walk through the core steps of building a solution, and provide practical tips, code examples, and links to extra resources.

Why This Topic Matters

Images add a lot of life to web applications. They help grab attention, tell a story, and make your content more engaging.

When images are stored in a database, it gives you control over how and where they are used.

For instance, imagine a content management system (CMS) or an e-commerce site that needs to handle lots of pictures.

Fetching these images from a central database means you can update or replace them without having to touch the client-side code.

It also provides a way to secure image storage and manage access permissions.

This process is not just about showing pictures—it’s about building a robust, interactive experience for your users.

As a developer, being able to fetch and display images efficiently can help make your application faster and more responsive.

When done right, it enhances the user experience and helps your site perform better in search engines like Google, which often favor pages that load quickly and provide engaging content.

A Step-by-Step Look at the Process

Let’s break down the process into manageable parts. I’ll focus on a common setup where the images are stored in a database (like MongoDB, MySQL, or PostgreSQL) and are served via a backend (using Node.js, Express, or any other framework) to a React front end.

1. Storing the Images in a Database

You might wonder, “How do I store images in a database?” There are two main approaches:

  • Storing Image URLs: Instead of saving the actual image in the database, you store the URL or path to the image. The images themselves are kept on a file server or cloud storage. This method keeps your database light and makes it easier to manage the images separately.
  • Storing Binary Data: In some cases, you might save the image as binary data (often in a field like BLOB).

This is less common due to database size and performance concerns, but it’s useful when you need a single source of truth for your data.

Each method has its benefits. For many projects, storing image URLs is the best option because it simplifies scaling and performance.

If you choose to store binary data, be mindful of the increased load on your database and the potential need for extra optimization.

2. Setting Up the Backend

The backend plays a crucial role in fetching images from the database and serving them to the frontend. A typical backend using Node.js and Express might look like this:

const express = require('express');
const app = express();
const port = 3000;
const db = require('./db'); // your database connection

app.get('/api/image/:id', async (req, res) => {
  try {
    const imageId = req.params.id;
    // If you store the image URL in the database:
    const imageData = await db.getImageData(imageId);
    res.json(imageData);

    // If you store binary data:
    // const imageData = await db.getImageBinary(imageId);
    // res.contentType('image/jpeg');
    // res.send(imageData);
  } catch (error) {
    res.status(500).json({ error: 'Image could not be retrieved.' });
  }
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

This example shows a simple route where a client can request an image by its ID.

The server then retrieves the data from the database and sends it back as a response.

Notice that if you’re dealing with binary data, you should set the correct content type (like image/jpeg).

3. Fetching and Displaying Images in React

Now let’s move to the frontend with React. Using the fetch API in a React component is straightforward. Here’s an example of how you might do it:

import React, { useState, useEffect } from 'react';

function ImageComponent({ imageId }) {
  const [imageSrc, setImageSrc] = useState('');

  useEffect(() => {
    async function fetchImage() {
      try {
        const response = await fetch(`/api/image/${imageId}`);
        const data = await response.json();

        // If your API returns a URL:
        setImageSrc(data.imageUrl);

        // If your API returns binary data, you might convert it to a Blob:
        // const blob = await response.blob();
        // setImageSrc(URL.createObjectURL(blob));
      } catch (error) {
        console.error('Error fetching the image:', error);
      }
    }

    fetchImage();
  }, [imageId]);

  return (
    <div>
      {imageSrc ? (
        <img src={imageSrc} alt="Fetched from DB" />
      ) : (
        <p>Loading image...</p>
      )}
    </div>
  );
}

export default ImageComponent;
Enter fullscreen mode Exit fullscreen mode

This React component demonstrates how to fetch image data when the component mounts. Depending on the API response, you either set the image source directly or create a URL from the blob data. This code is easy to understand and tweak based on your specific needs.

Practical Tips and Considerations

  • Caching: Consider using caching strategies to reduce the number of requests to your backend. Tools like service workers in React can help speed up image delivery.
  • Error Handling: Always include error handling in your code. It’s important to let your users know if something goes wrong, so they aren’t left staring at a broken image.
  • Performance: Optimize your images before uploading them to ensure they load quickly. Using formats like WebP can reduce file sizes without losing quality.
  • Security: Make sure your backend endpoints are secure. Use proper authentication and authorization methods, especially if the images are sensitive or proprietary.

Frequently Asked Questions

Can I store images in a database without affecting performance?

Storing images as binary data can impact database performance if not handled correctly. Often, it’s better to store image URLs and manage the images on a dedicated server or cloud storage.

How do I handle large images?

Large images can slow down your application. Optimize your images by compressing them, resizing them, or using lazy loading techniques in React to only load images when needed.

What if my React app does not show the image even though my API returns data?

Check that your image URL or blob data is correct. Make sure the backend sets the correct content type. Also, inspect the network requests in your browser to troubleshoot any issues.

Is it possible to add image processing on the backend before sending them to the frontend?

Yes, you can use libraries like Sharp in Node.js to process images (resize, compress, convert formats) before sending them out to the client.

6. Additional Resources

For more detailed guidance on React and image handling, you might find these links useful:

  • React Documentation

    The official React docs provide excellent tutorials and examples that cover many topics, including state management and lifecycle methods.

  • Express Documentation

    This site has comprehensive guides on setting up routes, handling requests, and working with middleware in Express.

  • MDN Web Docs on Fetch API

    This resource explains the fetch API in detail and offers examples on how to use it for making network requests.

  • Sharp: High Performance Node.js Image Processing

    Learn more about processing images on the backend if you need to handle large files or perform image manipulation.

  • Optimizing Web Images

    This article by Google explains best practices for optimizing images to boost your website’s performance.

Wrapping Up

I have walked you through the basics of fetching an image from a database and displaying it in a React application.

This process, while it might seem complex at first, becomes much easier when broken down into simple, manageable steps.

I explained the two common methods for storing images, how to set up a backend to serve those images, and how to fetch and display them in a React component.

I also offered some practical tips on caching, performance, and security, and answered some common questions about the process.

Using a friendly, straightforward approach helps make these technical topics more approachable.

The techniques discussed can be applied to various scenarios, from small personal projects to large-scale applications.

I have shared links to further resources and detailed documentation so you can explore these topics more deeply on your own.

It’s always good to keep learning and experimenting—each project brings new challenges and learning opportunities.

So, after reading this, what are your thoughts on building a feature to fetch and display images in React? How do you plan to integrate these ideas into your next project?

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Join the Runner H "AI Agent Prompting" Challenge: $10,000 in Prizes for 20 Winners!

Runner H is the AI agent you can delegate all your boring and repetitive tasks to - an autonomous agent that can use any tools you give it and complete full tasks from a single prompt.

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. ❤️