miamen
miamen

Reputation: 41

react-file-viewer re-render only if file type changed

I am using react-file-viewer in a sharepoint react-web part. It works fine, as long as the suffix of the file changes. If the suffix remains the same and only the filename changes there is no re-rendering in the react-file-viewer component.

Is there something special to consider in the spfx environment?

import * as React from 'react';
import FileViewer from 'react-file-viewer';
import { LibraryItem } from './LibraryItem';
//import { CustomErrorComponent } from 'custom-error';

export interface IDocumentViewProps {
  fileItem: LibraryItem;
  DocumentViewKey: any;
}

export default class DocumentView extends React.Component<IDocumentViewProps, any> {
  private path: string = "";
  private type: string = "";
  private fileItem: LibraryItem;

  constructor(props: IDocumentViewProps,any) {
    super(props);
    this.state = {
      path: '',
      suffix: ''
    };
  }

  private setFileComponents(item: LibraryItem) {
    if (item) {
      this.path = item.FileRef;
      this.type = item.File_x0020_Type;
      this.setState({ suffix: this.type });
      this.setState({ path: this.path });
    }
  }

  public componentWillReceiveProps(nextProps) {
    const { fileItem } = this.props;
    if (nextProps.fileItem !== fileItem) {
      this.fileItem = nextProps.fileItem;
      this.setFileComponents(this.fileItem);
    }
  }

  public render(): React.ReactElement<IDocumentViewProps,any> {
    return (
      <FileViewer
        fileType={this.state.suffix}
        filePath={this.state.path}
        // errorComponent={CustomErrorComponent}      
        onError={this.onError} 
        on
        />

    );
  }

  private onError(e) {
    // logger.logError(e, 'error in file-viewer');
    console.log(e, 'error in file-viewer');
  }
}

Upvotes: 2

Views: 1267

Answers (1)

miamen
miamen

Reputation: 41

Solution (workaround) ist to set key={currentFile.id}. I got this very helpful hint on github https://github.com/plangrid/react-file-viewer/issues/142 Thanks to https://github.com/yulolimum

Upvotes: 2

Related Questions