Download File in React

Code Examples, React Native, ReactJS

Download File in React

downloadFile = () => {
  fetch('https://example.com/pdf-file-url', {
    method: 'GET',
    headers: {
      'Content-Type': 'application/pdf',
    }
  })
  .then((response) => response.blob())
  .then((blobData) => {
    const url = window.URL.createObjectURL(
      new Blob([blobData]),
    );
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute(
      'download',
      `userFile.pdf`,
    );
    document.body.appendChild(link);
    link.click();
    link.parentNode.removeChild(link);
  });
}

click for more React codes, read about react doc