TypeError: Cannot set property 'src' of null

Viewed 560

I am trying to preview .docx file using react-file-viewer

<FileViewer
    fileType={'docx'}
    filePath={this.state.file} //this.state.file has path of the url data
    id="output-frame-id"
    allowFullScreen={true}
/>

When the user clicks on the .docx file for preview it throws an exception :

TypeError: Cannot set property 'src' of null

and points to the code below

let srcData = URL.createObjectURL(this.response); // It contains a Response type of blob
error at this line ---> document.querySelector('#output-frame-id').src = srcData;

Any suggestions ?

2 Answers

https://github.com/plangrid/react-file-viewer

source code

 FileViewer.propTypes = {
      fileType: PropTypes.string.isRequired,
      filePath: PropTypes.string.isRequired,
      onError: PropTypes.func,
      errorComponent: PropTypes.element,
      unsupportedComponent: PropTypes.element,
    };
    
    FileViewer.defaultProps = {
      onError: () => null,
      errorComponent: null,
      unsupportedComponent: null,
    };

I don't see in documentation id field, maybe that's why your selector return null.

You should use only this field: fileType, filePath, onError, errorComponent, unsupportedComponent.

If you want for some reason DOM manipulations with element, for this you can wrap your element by div:

<div id="output-frame-id"
    <FileViewer
        fileType={'docx'}
        filePath={this.state.file} //this.state.file has path of the url data
        allowFullScreen={true}
    />
</div>

But i recommend use refs

I think this is happening because

document.querySelector('#output-frame-id') // equal to null

Can you check in developer tool does React really render element with such id - output-frame-id? I know you have this id in your component, but it not necessary that React will render it... It depends of realization of FileViewer, this component might not support id attribute because this is a custom component.

I am not sure but, you can try to use:

  1. use refs
  2. use colon before id
:id="output-frame-id"
Related