DEV Community

Amrita-padhy
Amrita-padhy

Posted on

Enhancing React Apps: Server Image Preview Component

In this blog post, we'll walk through the process of creating a custom file preview component using React. We won't rely on any third-party libraries, ensuring you gain a deeper understanding of how to handle files directly in JavaScript. By the end of this tutorial, you'll be able to preview images, text files, xlxs files, pdf files in your React application.

const PdfViewer = ({ url }) => {
  const iframeRef = useRef(null);
  const interval = useRef();

  const pdfUrl = createGdocsUrl(url);

  const [loaded, setLoaded] = useState(false);

  const clearCheckingInterval = () => {
    clearInterval(interval.current);
  };

  const onIframeLoaded = () => {
    clearCheckingInterval();
    setLoaded(true);
  };

  useEffect(() => {
    interval.current = setInterval(() => {
      try {
        // google docs page is blank (204), hence we need to reload the iframe.
        if (iframeRef.current.contentWindow.document.body.innerHTML === '') {
          iframeRef.current.src = pdfUrl;
        }
      } catch (e) {
        // google docs page is being loaded, but will throw CORS error.
        // it mean that the page won't be blank and we can remove the checking interval.
        onIframeLoaded();
      }
    }, 4000); // 4000ms is reasonable time to load 2MB document

    return clearCheckingInterval;
  }, []);

  return (
    <div className={css['pdf-iframe__wrapper']}>
      <iframe
        ref={iframeRef}
        className={css['pdf-iframe__inside']}
        frameBorder="no"
        onLoad={onIframeLoaded}
        src={pdfUrl}
        title="PDF Viewer"
      />

      {!loaded && (
        <div className={css['pdf-iframe__skeleton']}>
          <Skeleton height="100%" rectRadius={{ rx: 0, ry: 0 }} width="100%" />
        </div>
      )}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

In this blog post, we created a custom file preview component using React without relying on any third-party libraries. We learned how to read file contents, and display previews .

Potential enhancements include adding support for more file types, improving the styling, and handling errors more gracefully. Happy coding!

Feel free to reach out in the comments if you have any questions or suggestions!

Top comments (0)