October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

How to Build a Reusable Image Component in React

Create a small React wrapper around the native img element, with accessible alt text, responsive image options, layout-stable dimensions, and optional fallback handling.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A React image component is a small wrapper around the browser’s native <img> element. Start by requiring a source and meaningful alt text, then forward the native image props your app needs. Add responsive sources, dimensions, lazy loading, or an error fallback only when they solve a real requirement.

Start with a reusable native image wrapper

React supports <img> directly; a custom component is optional. A wrapper is useful when it makes your project’s accessibility and layout conventions easier to follow.

This JavaScript component accepts the source and alternative text explicitly, then forwards standard image attributes such as dimensions, responsive-source hints, loading behavior, and event handlers:

function Image({ src, alt, ...imgProps }) {
  return <img src={src} alt={alt} {...imgProps} />;
}

export default function Article() {
  return (
    <Image
      src="/images/harbor.jpg"
      alt="Boats moored in a harbor at sunset"
      width={1200}
      height={800}
      className="article-image"
    />
  );
}

Because the wrapper spreads the remaining props onto the native element, callers can use React’s supported image props without the component needing a separate prop for every browser feature. If you add defaults or custom behavior, keep the API clear about which native attributes are still accepted.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose alt text for the image’s purpose

For an informative image, provide a concise alternative that communicates the information the image contributes in its context. Do not generate alt text from a filename: names such as harbor-final-2.jpg rarely describe the image’s meaning.

<Image
  src="/images/harbor.jpg"
  alt="Boats moored in a harbor at sunset"
/>

If an image is purely decorative and adds no information, use an empty string so assistive technology can skip it:

<Image src="/images/flourish.svg" alt="" />

Do not omit alt just because the image is decorative. An empty value is an intentional text alternative. For guidance on choosing alternatives, see the W3C/WAI Images Tutorial.

Set dimensions to reserve layout space

Provide the image’s intrinsic width and height when known. The browser can use them to reserve space before downloading the image, helping avoid layout shifts, including when an image is lazy-loaded. These values describe the image’s intrinsic dimensions; CSS can still size it to fit a responsive layout.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<Image
  src="/images/harbor.jpg"
  alt="Boats moored in a harbor at sunset"
  width={1200}
  height={800}
  style={{ maxWidth: "100%", height: "auto" }}
/>

See MDN’s <img> reference for the browser element’s attributes and behavior.

Choose how the browser selects image resources

Use src for one suitable resource

A single src is the simplest choice when one image resource is appropriate for every rendered size.

Use srcSet and sizes for resolution choices

When you have multiple resolutions of the same image, srcSet lists candidate files and their intrinsic widths. sizes describes the image’s expected rendered slot width at different viewport sizes. The browser uses both hints to choose a candidate; the values should reflect the files and layout you actually provide.

<Image
  src="/images/harbor-800.jpg"
  srcSet="/images/harbor-400.jpg 400w, /images/harbor-800.jpg 800w, /images/harbor-1200.jpg 1200w"
  sizes="(max-width: 600px) 100vw, 800px"
  alt="Boats moored in a harbor at sunset"
  width={1200}
  height={800}
/>

Do not add candidate widths that do not match the actual image files, or a sizes value that misrepresents the layout. Read MDN’s responsive images guide for the selection model.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use <picture> for different sources or art direction

Use the native <picture> element with one or more <source> elements when conditions should select a different format, crop, or image source. Keep an <img> inside it as the fallback and place the alternative text on that image:

<picture>
  <source media="(max-width: 600px)" srcSet="/images/harbor-close.jpg" />
  <source type="image/webp" srcSet="/images/harbor.webp" />
  <img
    src="/images/harbor.jpg"
    alt="Boats moored in a harbor at sunset"
    width="1200"
    height="800"
  />
</picture>

Use a plain wrapper for the uncomplicated case; a component that supports art direction may need to render <picture> rather than only <img>.

Lazy-load only images that can wait

For an image below the fold that does not need to appear immediately, pass loading="lazy". Do not automatically apply it to an image needed in the initial viewport, because deferring that request can delay its display. Continue to provide dimensions so the browser can reserve its space.

<Image
  src="/images/harbor.jpg"
  alt="Boats moored in a harbor at sunset"
  width={1200}
  height={800}
  loading="lazy"
/>

React documents loading, fetchPriority, and other native image props in its image component reference. For server-rendered pages, React can emit an image preload hint automatically; loading="lazy" and fetchPriority="low" prevent that automatic hint for the image. Frameworks may wrap or change image behavior, so consult the documentation for your framework’s image component if you use one.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Add an error fallback only if the interface needs one

Use React’s onError when the interface should respond to a failed image request, such as by showing a local placeholder. Keep fallback state local to the component, and do not render an empty src: React notes that an empty source can make the browser request the current page.

import { useState } from "react";

function ImageWithFallback({ src, alt, fallbackSrc, ...imgProps }) {
  const [failed, setFailed] = useState(false);

  return (
    <img
      src={failed ? fallbackSrc : src}
      alt={alt}
      onError={() => setFailed(true)}
      {...imgProps}
    />
  );
}

This minimal version assumes the fallback resource is valid. If it also fails, the same handler runs again; avoid an endless retry by tracking whether the fallback has already failed or by using a known-good local asset. Ensure caller-supplied props cannot accidentally replace the component’s failure handler: in the example, onError is set before the spread, so an onError in imgProps would override it. One safer explicit API is to capture and compose the caller’s handler:

import { useState } from "react";

function ImageWithFallback({ src, alt, fallbackSrc, onError, ...imgProps }) {
  const [failed, setFailed] = useState(false);
  const [fallbackFailed, setFallbackFailed] = useState(false);

  function handleError(event) {
    if (!failed && fallbackSrc) {
      setFailed(true);
    } else {
      setFallbackFailed(true);
    }
    onError?.(event);
  }

  if (fallbackFailed) {
    return null;
  }

  return (
    <img
      src={failed ? fallbackSrc : src}
      alt={alt}
      onError={handleError}
      {...imgProps}
    />
  );
}

This example removes the image after the fallback itself fails; replace null with an accessible error state if the page needs to explain the missing content. Decide how such a state should be presented rather than silently retrying indefinitely.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Pick the simplest option that meets the page’s needs

Approach Use it when Trade-off
Plain src One resource suits the image’s rendered sizes. Simplest markup; no responsive candidate set.
srcSet plus sizes The same image has multiple resolutions and its slot width varies. Requires accurate candidate widths and slot-size hints.
<picture> with <source> A different crop, format, or image source should apply under conditions. Adds markup and source-selection rules.
loading="lazy" An image is below the fold and can wait until near the viewport. Can delay an image needed immediately; include dimensions to reserve space.

These are browser-supported choices, not a universal speed ranking. Which is appropriate depends on the page layout and available image resources.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshoot common problems

  • The image has no useful accessible description: write context-appropriate alt text for informative images; use alt="" for decorative ones.
  • The page shifts when the image appears: set the intrinsic width and height so space can be reserved before loading.
  • The wrong resolution is selected: verify that srcSet width descriptors match the actual files and that sizes reflects the rendered slot.
  • An important image appears late: remove lazy loading from an image needed immediately in the initial viewport.
  • The fallback repeats or fails too: track fallback failure separately and show a deliberate error state rather than repeatedly assigning a broken URL.
  • The current page is requested as an image: check that no render path supplies an empty src; provide a real source or render an intentional alternative.

Or skip the browser setup

If you need screenshots of a webpage rather than an image element inside your React UI, ScreenshotNeo provides a website screenshot API. One GET request returns an image or PDF. For example, using cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. Before capture, it accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.