File Viewer In Spfx Using React💯

Introduction

 
react-file-viewer is a powerful plugin written in React.js to open pdf, png, docx, csv, mp3, mp4 and xlsx files.
 
Open a command prompt. Create a directory for the SPFx solution.
 
md spfx-ReactFileViewer
 
Navigate to the above-created directory.
 
cd spfx-ReactFileViewer
 
Run the Yeoman SharePoint Generator to create the solution.
 
yo @microsoft/sharepoint
 
Solution Name
 
Hit Enter to have the default name (spfx-ReactFileViewerin this case) or type in any other name for your solution.
Selected choice - Hit Enter
 
Target for the component
 
Here, we can select the target environment where we are planning to deploy the client web part; i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice - SharePoint Online only (latest).
 
Place of files
 
We may choose to use the same folder or create a subfolder for our solution.
Selected choice - same folder.
 
Deployment option
 
Selecting Y will allow the app to be deployed instantly to all sites and be accessible everywhere.
Selected choice - N (install on each site explicitly).
 
Permissions to access web APIs
 
Choose if the components in the solution require permission to access web APIs that are unique and not shared with other components in the tenant.
Selected choice - N (solution contains unique permissions)
 
Type of client-side component to create
 
We can choose to create a client-side web part or an extension. Choose the web part option.
Selected choice - WebPart
 
Web part name
 
Hit Enter to select the default name or type in any other name.
Selected choice - ReactFileViewer
 
Web part description
 
Hit Enter to select the default description or type in any other value.
 
Framework to use
 
Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
Selected choice - React
 
The Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running the below command,
 
npm shrinkwrap
 
In the command prompt, type the below command to open the solution in the code editor of your choice.
  1. npm i react-file-viewer  
 Optional Installation for style
  1. npm i csstype  
Necessary imports
  1. import FileViewer from 'react-file-viewer';  
  2. import * as CSS from 'csstype';   
Full Code
 
in ReactFileViewer.tsx
  1. import * as React from 'react';  
  2. import { IReactFileViewerProps } from './IReactFileViewerProps';  
  3. import FileViewer from 'react-file-viewer';  
  4. import * as CSS from 'csstype';  
  5. let myfile:string = '';  
  6. let mytype:string = '';  
  7. interface IPnpstate {      
  8.   file:string;    
  9.   type:string;  
  10. }   
  11. var divStyle: CSS.Properties = {  
  12. minHeight:'auto'  
  13. };  
  14. export default class ReactFileViewer extends React.Component<IReactFileViewerProps, IPnpstate> {  
  15.  // private  recaptchaRef = React.createRef<HTMLInputElement>();    
  16.  constructor(props: IReactFileViewerProps, state: IPnpstate) {    
  17.   super(props);    
  18.   this.state = {    
  19.   file:'/Shared%20Documents/Total_Crime.csv',  
  20.   type :'csv'  
  21.   };  
  22.    
  23. }  
  24.   public componentDidMount() {  
  25.     (document.querySelector("#FileViewer") as HTMLOptionElement).addEventListener('change', (e) =>{  
  26.      let mytargetoption = (e.target as HTMLTextAreaElement).value;  
  27. switch (mytargetoption) {  
  28.   case 'pdf':  
  29.     myfile="/Shared%20Documents/sample.pdf";  
  30.     mytype="pdf";  
  31.     break;  
  32.     case 'csv':  
  33.       myfile="/Shared%20Documents/Total_Crime.csv";  
  34.       mytype="csv";  
  35.       break;   
  36.       case 'png':  
  37.         myfile="/Shared%20Documents/teams.png";  
  38.         mytype="png";  
  39.       break;   
  40.       case 'xlsx':  
  41.         myfile="/Shared%20Documents/Financial Sample.xlsx";  
  42.         mytype="xlsx";  
  43.       break;   
  44.       case 'docx':  
  45.         myfile="/Shared%20Documents/11KB.docx";  
  46.         mytype="docx";  
  47.       break;  
  48.   default:  
  49.     console.log('file fromat not found');  
  50. }  
  51. this.setState({ file: myfile,type: mytype });  
  52.   
  53.     }  
  54.     //,{ once: true }  
  55.   );  
  56.   }  
  57.   public render(): React.ReactElement<IReactFileViewerProps> {  
  58.     return (  
  59.       <div  style={divStyle}>  
  60.            <select id="FileViewer">  
  61.   <option value="pdf">PDF</option>  
  62.   <option value="xlsx">XLSX</option>  
  63.   <option value="png">PNG</option>  
  64.   <option value="docx">DOCX</option>  
  65.   <option value="csv">CSV</option>  
  66. </select>  
  67.  <FileViewer   
  68.         fileType={this.state.type}  
  69.         filePath={this.state.file}  
  70.     />  
  71.       </div>  
  72.     );  
  73.   }  
  74. }  

 Properties

  • fileType-type of the file where pdf,png,mp3 etc(Mandatory)
  • filepath-path of the file (where cors is not supported) (Mandatory)
  • onError- function that will be called when there is an error in the file viewer fetching or rendering the requested resource. (Optional)
  • errorComponent- A component to render in case of error instead of the default error component that comes packaged with react-file-viewer.(Optional)
  • unsupportedComponent - A component to render in case the file format is not supported. (Optional)
The Where plugin has some size issue in image,xlsx,csv format in current version. I hope it will be solved in the next release.
 
Expected Output
 
File Viewer In Spfx Using React
File Viewer In Spfx Using React
 

Conclusion

 
Hence we learned how to implement fileviewer in spfx using react plugin react-file-viewer. I hope this helps someone. Happy coding :)