Sequence NODE_196
Medium

Build a File Upload Preview (No Backend)

React
JavaScript
Technical Specification

Create a file input that shows a preview of an image file selected by the user.

Input/Output Samples
Input:Select image file
Output:Preview image displayed
Optimal Logic Path
import { useState } from "react";

function ImageUploadPreview() {
  const [src, setSrc] = useState("");

  function onChange(e) {
    const file = e.target.files && e.target.files[0];
    if (!file || !file.type.startsWith("image/")) return;
    const url = URL.createObjectURL(file);
    setSrc(url);
  }

  return (
    <div>
      <input type="file" accept="image/*" onChange={onChange} />
      {src && <img src={src} alt="Preview" style={{ maxWidth: "200px" }} />}
    </div>
  );
}
Architectural Deep-Dive
We generate a temporary URL for the selected file and use it as the img src.