Ad

How To Do Vanilla Js Equivalent AppendChild In React?

- 1 answer

I have already written this pen in vanilla js. Now I want to use it inside my react component.

renderPDF(url, canvasContainer, options) {
  options = options || {
    scale: 1
  };

  function renderPage(page) {
    var viewport = page.getViewport(options.scale);
    var wrapper = document.createElement("div");
    wrapper.className = "canvas-wrapper";
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    var renderContext = {
      canvasContext: ctx,
      viewport: viewport
    };
    canvas.height = viewport.height;
    canvas.width = viewport.width;
    wrapper.appendChild(canvas);
    canvasContainer.appendChild(wrapper);

    page.render(renderContext);
  }

  function renderPages(pdfDoc) {
    for (var num = 1; num <= pdfDoc.numPages; num++)
      pdfDoc.getPage(num).then(renderPage);
  }
  PDFJS.disableWorker = true;
  PDFJS.getDocument(url).then(renderPages);
}

When i use the above render function inside componentDidMount lifecycle of react, am getting the error of Cannot read property 'appendChild' of null

Please guide me to code the above function in the react way?

Here is my current code-sandbox

Ad

Answer

Your Modal component not render at first time because of this.state = {visible: false}; so .modal-container does not exist at first render. It will be rendered only after your click on 'Open' button.

To avoid this you could move pdf creation logic into separate component and render this component inside <Modal>. Here is an example

Ad
source: stackoverflow.com
Ad