React-file-viewer in SPFX

·

2 min read

Purpose

Sharepoint users have standard webparts to display a file in a communication site.But to display file from other sites in your tenant or to preview a document without opening them. I explored few libraries to implement these type of functionality and I found one good library i.e, react-file-viewer

Introduction

react-file-viewer is a npm library. Generally we need to download various libraries for various file types. But react-file-viewer library various file types such as Images( png, jpeg, gif, bmp, including 360-degree images),pdf, csv, xslx, docx, Video: mp4, webm, Audio: mp3 PDF is the one of the important file type whicheveryone is using.However people use various file types in document libraries specifically microsoft users To install this library,run the below command in your webpart

npm i react-file-viewer

Example

Here I will show you how to use react-file-viewer in spfx

  • Install the library by using the above command
  • Write below statement in .tsx file(if react framework based webpart) or in .ts file(if no javascript framework based webpart).
    import FileViewer from 'react-file-viewer';
    
  • Generally file viewer is like component which requires two main parameters

       <FileViewer
         fileType='png' //mandatory
         filePath='http://example.com/image.png' //mandatory
         errorComponent={CustomErrorComponent} //optional
         onError={this.onError} //optional
       />
    

    How I implement this in my spfx webpart.

  • I created a webpart with react framework.

  • I am getting file type and file path whic is required to pass into component fromproperty pane configuration.

image.png

from here I passed them as 'props' into tsx file

  • And in tsx file give those props to component

image.png output

Give file path and file type

image.png

PDF file will render as follows

image.png

Xlsx file will render as follows

image.png

Pros & Cons

image.png

Conclusion

Although react-file-viewer is not a great file viewing library, it is nevertheless useful.

It's worthwhile to give it a shot when looking for a file viewer library.

Reference

react-file-viewer npmjs.com/package/react-file-viewer