Skip to main content

useObjectUrl

Creates an URL for the provided File, Blob, or MediaSource via URL.createObjectURL() and automatically releases the URL via URL.revokeObjectURL() when the source changes or the component is unmounted

Usage

Live Editor

function Demo() {
  const [file, setFile] = useState<File>();
  const url = useObjectUrl(file);

  const onFileChange = (e: ChangeEvent<HTMLInputElement>) => {
    const target = e.target;
    const files = target.files;
    setFile(files && files.length > 0 ? files[0] : undefined);
  };
  return (
    <div>
      <p>Select File</p>
      <input type="file" onChange={onFileChange} />
      <p>Object Url</p>
      <div>{url}</div>
    </div>
  );
};

Result
Loading...

API

useObjectUrl

Returns

string | undefined: Returns a URL created from the Blob or MediaSource object, or undefined if none exists

Arguments

ArgumentDescriptionTypeDefaultValue
objectfile or media sourceBlob | MediaSource (Required)-