Skip to content

Instantly share code, notes, and snippets.

@leonardof02
Last active February 2, 2024 20:35
Show Gist options
  • Select an option

  • Save leonardof02/2a31366a42cb69cdc03e99ebf4c49e5c to your computer and use it in GitHub Desktop.

Select an option

Save leonardof02/2a31366a42cb69cdc03e99ebf4c49e5c to your computer and use it in GitHub Desktop.
React Hooks that made my life easier
/* eslint-disable react-hooks/exhaustive-deps */
import { useState, useEffect } from "react";
/**
* Hook para visualizar la imagen pasada como parametro a traves de su URL
* @param imageFile La imagen en formato de archivo (File o Blob)
* @returns Un url que respresenta la vista de la imagen (Ej: `<img src={previewUrl}/>` mostrará la imagen)
*/
export default function useImagePreview(imageFile?: File[]) {
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
useEffect(() => {
if (imageFile?.[0] && !previewUrl) {
const objectUrl = URL.createObjectURL(imageFile[0]);
setPreviewUrl(objectUrl);
return;
}
}, [imageFile]);
return previewUrl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment