Using instance.loadDocument() inside useEffect to open a file

PDF.js Express Version

Detailed description of issue
{User can select a PDF to view in the webViewer from the dropdown. The flow is much like the example provided here:, but implemented in ReactJs. When another file is selected an error is thrown: Unhandled Rejection (Error): Two instances of WebViewer were created on the same HTML element. Please create a new element for each instance of WebViewer.
What am I missing and how to fix it? }

Expected behaviour
{ Selected document should be loaded into WebViewer without any errors. }

Link to document
{Provide a link to the document in question if possible}

Code snippet
const viewer = useRef(null);

const [pdf, setPdf] = useState(undefined)

const docs = [


        id: '0',

        text:'PDF-tron test',

        path: '/files/PDFTRON_about.pdf'



        id: '1',


        path: '/files/ABY_PP_AR-5-0204.pdf'


let defaultFilePath = !!pdf ? docs.filter(x => {return === pdf}) : docs[0]

useEffect(() => {



        path: '/webviewer/lib',

        initialDoc: defaultFilePath.path,



    ).then((instance) => {

        const file = docs.filter(x => {return === pdf})



            console.log(file, file[0].path)




}, [pdf] );



Since your reference to pdf is changing, that useEffect hook is getting rerun which in turn is remounting WebViewer. You will have to pull that logic into it’s own useEffect.

const [instance, setInstance] = useState(null)
useEffect(() => {
   WebViewer(...).then(instance => {
}, [])

useEffect(() => {
     if(instance && pdf) {
}, [pdf, instance])

I recommend taking a look at the React docs and learning the ins and outs of the dependecy arrays!


1 Like

Thanks a lot! :pray:

1 Like