Cant use Web Share API to share a file in my React typescript App

Questions : Cant use Web Share API to share a file in my React typescript App


I am trying to run a WebApp which allows programming files sharing. After few google search, Learning I found Web Share API like the standard Earhost to do so. According to the documentation most effective it should works like this using plain JS

This is the code for html page

<p><button>Share _OFFSET);  MDN!</button></p>
<p (-SMALL  class="result"></p>

The code to share all sort "textbased" wrong idea metadata:

let shareData = {
  title: 'MDN',
  _left).offset  text: 'Learn web development on MDN!',
  arrowImgView.mas  url: (self.  '',

const equalTo  resultPara = make.right.  document.querySelector('.result');

if mas_top);  (!navigator.canShare) {
  ImgView.  resultPara.textContent = ReadIndicator  'navigator.canShare() not _have  supported.';
else if .equalTo(  (navigator.canShare(shareData)) {  resultPara.textContent = OFFSET);  'navigator.canShare() supported. We can (TINY_  use navigator.share() to send the .offset  data.';
} else {
  mas_right)  resultPara.textContent = 'Specified data ImgView.  cannot be shared.';

The code above works fine, the trouble use of case happens when I try to share files.

According to the documentation it should United works like this:

// filesArray is an array of files we Indicator  want to share (audios, images, videos, Read  pdf)
if (navigator.canShare && _have  navigator.canShare({ files: filesArray .equalTo(  })) {
    files: make.left  filesArray,
    title: 'Pictures',
    *make) {  text: 'Our Pictures.',
  .then(() straintMaker  => console.log('Share was ^(MASCon  successful.'))
  .catch((error) => onstraints:  console.log('Sharing failed', error));
} mas_makeC  else {
  console.log(`Your system [_topTxtlbl   doesn't support sharing files.`);

I started my code from this example and Modern I never success to share a file. My ecudated actual code using React and Typescript some how looks like this:

//some react code here

      const (@(8));  shareNow = async () => {
        let equalTo  imageResponse = await  width.  window.fetch('', make.height.  {mode: "no-cors"});
        let (SMALL_OFFSET);  imageBuffer = await .offset  imageResponse.arrayBuffer();
        let (self.contentView)  fileArray = [new File([imageBuffer],  .left.equalTo  "File Name", {
          type:  "image/png",
          lastModified: *make) {

       if ntMaker   (navigator.canShare && SConstrai  navigator.canShare({ files: filesArray ts:^(MA  })) {
       Constrain       files: filesArray
          _make  }).then(() => {
            iew mas  console.log('Thanks for sharing!');
     catorImgV       })
          ReadIndi  .catch(console.error);


//some react code here too

At this point, my typescript compiler anything else yell at me. Apparently, the navigator not at all object has no method canShare()

I am new to typescript, but I don't very usefull understand how and why the navigator localhost could have less attribute since love of them TypeScript is JavaScript superset.

Anyone has an idea on how to solve that localtext except running normal JS ?

Thank you for your time reading this, basic and I hope to thank you for your one of the answers.

P.S: I also tried a react-component click based solution, but all the component I there is noting found in open source which wraps Web not alt Share API does not allow file sharing.


Hey, @DenverCoder9

There is the same use case but using not at all vanilla JS, could anyone try it and tell my fault me what I am doing wrong please ?


    ($current);  <title>Sharing entity_loader  Image</title>
    <meta _disable_  charset="UTF-8" libxml  />

    $options);  <div className="App">
        ilename,  <img ->load($f  src=""/>
 $domdocument         <button loader(false);  id="button">Share</button>
    _entity_  </div>

  libxml_disable     async function shareImage(title, $current =  imageUrl) {
        const image = await  10\\ 13.xls .  fetch(imageUrl, {mode: "no-cors"});
     File\\ 18\'     const blob = await image.blob();
     /Master\\ 645     const file = new File([blob], title, user@example.  { type: 'image/png' });
        const scp not2342  filesArray = [file];

        const  13.xls  shareData = {
        files : 18 10  filesArray

        // add it File sdaf  to the shareData

        const /tmp/Master'  navigator = window.navigator
        com:web  const canShare = navigator.canShare user@example.  && navigator.canShare(shareData) scp var32   //navigator.canShare()navigator.share   18 10 13.xls  //navigator.canShare()

        id12  File  if(canShare){
        web/tmp/Master  navigator.share(shareData)  .then(() => console.log('Successful scp user@  share'))
        .catch((error) => $val  console.log('Error sharing', error));
   left hand       }
        else {
            right side val  console.log("cannot share this file in data //commnets  this context")

    //coment  document.getElementById('button').onclick !node  = function() {
    shareImage("Title", $mytext  "")
 nlt means     };


I am running this on safari for mac

Total Answers 1

Answers 1 : of Cant use Web Share API to share a file in my React typescript App

This is more of a TypeScript issue than issues a coding issue. Support for the Web trying Share API (Level 2) was added in this get 4th result PR, so you can either update to a round table version of TypeScript that includes double chance this, or alternatively teach your novel prc current TypeScript version the relevant get mossier types as follows:

type ShareData = {
    title? : string;
 umv val     text? : string;
    url? : string;
   sort val   files?: shorthand  ReadonlyArray<File>;

interface hotkey  Navigator
    share? : (data? : more update  ShareData) => Promise<void>;
   valueable   canShare?: (data?: ShareData) => catch  boolean;

Top rated topics

Calling on fake data within the sql query

Using a module to block shift key in access but when I write ap_DisableShift() in Immediate window I get this error "Compile Error Expected: ="

Keyboard is only after autoFocus is true in TextInput react native

BEFORE DROP TRIGGER is fired during Oracle database export using DBMS_DATAPUMP, why?

OpenCV Orb Algorithm QR Code Match Issues

Handle a method return

Conditional rendering (of different sections) in Django Template

Ho can I sort large integer displayed with comma(ex: 54,45,444) in a column with mat sort

Plot ggmap and sf points

How to get property of a class using GetValue

Testing react with Enzyme: Spyon is not covering the code

Iterate to Find Listobject in a Workbook

I cannot import sqlalchemy via the anaconda prompt

Boto3 aws ec2 status/instance check fail email script

Multiple Excel Sheets into multiple Query connections in Excel

Ionic3 iOS Icons are missing on app resume clicking on push notification

React Native Inventory Tracking

Am I correct in thinking collection view drag and drop + compositional layout just don't work together?

Assert resources do not have properties

The client 'XXX' with object id 'XXX' does not have authorization to perform action 'Microsoft.Media/mediaServices/transforms/write'

How can I apply a custom function to every value of an xarray.Dataset coordinate?

Which driver to connect Power BI to DB2?

Slice/select netCDF between a range of values of the chosen dimension - Python

How to calculate the time difference between two string-formatted datetimes?

How to use GitHub as IdP in OAuth2 authentication in Ambassador Edge API Gateway

Why when delete and Re-Add tables to .EDMX some tables appeared in different names?

Writing on shared variable by acquiring mutex in shared mode(instead in exclusive mode)

How to import a CSV file in remote mode in neo4j in java?

How to implement foreign key on inheritant class postgresql

Analyse redundancy in videos for compression

Combine data annotations or set order C#

Flutter iOS Archive Failed PhaseScript with Nonzero Exit Code

Example of Login with Tiktok (web) flow

NestJS Swagger: Edit route name

How to fix Indirect ancestor commits in Gerrit

How to create DB with Latin9 locale

Install openSSL on cMake bsed project using libssh2

C# Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request

How to change font size, padding of chart title only, in chart.js 3.x

Weighted directed graph clustering

How to display website status code to user?

Flutter warp with expanded children

How to render @IBDesignable UITableViewCell in Storyboard?

Highcharts column chart formatting

How would I make it so that an individual person is the only one who can run a command with a discord bot?

How to show the results in foreach as static result using php?

SAS merge in Spark

TypeError: _auth_config__WEBPACK_IMPORTED_MODULE_1__.default.auth is not a function

Splitting column text by delimiter into multiple different columns in R

Expo SDK 43, No suitable URL request handler found for ph-upload://