Spreadsheet - Open an External URL file Example as a Functional Component

The example here is a Class Component, and admittedly I am struggling to convert this to a Functional Component.  Does anyone have any examples they can share that successfully converted this to a functional component?

https://ej2.syncfusion.com/react/documentation/spreadsheet/open-save/#open-an-external-url-excel-file-while-initial-load

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { SpreadsheetComponent } from '@syncfusion/ej2-react-spreadsheet';

export default class App extends React.Component<{}, {}> {
    spreadsheet: SpreadsheetComponent;
    public created(args): void {
        fetch("https://js.syncfusion.com/demos/ejservices/data/Spreadsheet/LargeData.xlsx") // fetch the remote url
                .then((response) => {
                    response.blob().then((fileBlob) => { // convert the excel file to blob
                    var file = new File([fileBlob], "Sample.xlsx"); //convert the blob into file
                    this.spreadsheet.open({ file: file }); // open the file into Spreadsheet
                    })
                })
    }
     render() {
        return  (<SpreadsheetComponent ref={(ssObj) => { this.spreadsheet = ssObj }}
                        openUrl='https://ej2services.syncfusion.com/production/web-services/api/spreadsheet/open' created={this.created.bind(this)}>
                    </SpreadsheetComponent>);
    }
}
ReactDOM.render(<App />, document.getElementById('root'));

3 Replies

SP Sangeetha Priya Murugan Syncfusion Team August 26, 2022 01:11 PM UTC

Hi Keith,


As per your requirement we have rendered the spreadsheet as a functional component as like as below.


Code Block:


 

import * as React from 'react';

import { getComponent } from '@syncfusion/ej2-base';

 

import { SpreadsheetComponent } from '@syncfusion/ej2-react-spreadsheet';





function Home(this: any) {

 

    // spreadsheet: SpreadsheetComponent;

    function created() {

        const spreadsheet: SpreadsheetComponent = getComponent(

            document.querySelector('.e-spreadsheet') as HTMLElement,

            'spreadsheet'

        );

 

        fetch("https://js.syncfusion.com/demos/ejservices/data/Spreadsheet/LargeData.xlsx") // fetch the remote url

            .then((response) => {

                response.blob().then((fileBlob) => { // convert the excel file to blob

                    const file = new File([fileBlob], "Sample.xlsx"); // convert the blob into file

                    spreadsheet.open({ file: file }); // open the file into Spreadsheet

                })

            })

    }

 

    return (<div> <p>Spreadsheet using Functional Components</p>

        <SpreadsheetComponent

            openUrl='https://ej2services.syncfusion.com/production/web-services/api/spreadsheet/open' created={created}/>

       

    </div>

    )

}

 

export default Home;

 


For your convenience, we have prepared the sample based on our suggestion. In this we have render the spreadsheet in Home.tsx page. Please find the link below.


Sample Link:
https://www.syncfusion.com/downloads/support/directtrac/general/ze/Functional-Components-in-React-master170164533


Could you please check the above link and get back to us, if you need any further assistance on this.


Regards,

Sangeetha M



KR Keith Rosenbauer August 26, 2022 04:46 PM UTC

Ok, so it looks like my issue was actually the fact that I didn't specify the openUrl in the SpreadsheetComponent.


But my implementation was slightly different than your code (BTW - thanks for the quick response and feedback on this!)

Basically, I have a component for the SpreadsheetComponent, but I noticed the 'ref' in the demo, so built mine with a useRef hook. Is there a reason to use the getComponent method provided by @syncfusion/ej2-base vs. using a useRef? So my code looks like this.


*** Parent component calling my Spreadsheet Component -> passing in the file details **

....

} else if (isSheetDocument) {
return <SpreadsheetViewer modalAttachment={modalAttachment} />;
}

....


*** My Spreadsheet Component with the useRef hook -> which is working now that I have the openURL specified***

/*************************/
/** Material UI Imports **/
/*************************/
// MUI Core
import { makeStyles } from '@material-ui/core';
/**************************/
/** React / Next Imports **/
/**************************/
import { useContext, useEffect, useMemo, useState, useRef } from 'react';
/***********************/
/** 3rd Party Imports **/
/***********************/
import { getComponent } from '@syncfusion/ej2-base';
import { SpreadsheetComponent } from '@syncfusion/ej2-react-spreadsheet';
/*******************************/
/** Internal Platform Imports **/
/*******************************/
// Components
// Types
import { ModalFile } from '../../types/attachment';

const useStyles = makeStyles(theme => ({
root: {
height: '100%',
width: '100%',
gridTemplateRows: '.25fr 2.5fr',
},
parent: {
width: '100%',
paddingLeft: 50,
paddingRight: 50,
paddingTop: 10,
pointerEvents: 'auto',
overflowY: 'scroll',
},
}));

interface SpreadsheetViewerProps {
modalAttachment: ModalFile;
}

const SpreadsheetViewer = ({ modalAttachment }: SpreadsheetViewerProps) => {
const classes = useStyles();

//**DELETE - just for testing */
console.log('modalAttachment', modalAttachment);

// establish spreadsheet Ref
const spreadsheet = useRef<null | SpreadsheetComponent>(null);

const onCreated = async () => {
// download file and open in spreadsheet
const downloadedFile = await fetch(modalAttachment.fileURL)
.then(r => r.blob())
.then(
blobFile =>
new File([blobFile], modalAttachment.attachment.originalFilename, {
type: modalAttachment.attachment.mimetype,
}),
);

spreadsheet?.current?.open({ file: downloadedFile });
};

// const onCreated = () => {
// const spreadsheet: SpreadsheetComponent = getComponent(
// document.querySelector('.e-spreadsheet') as HTMLElement,
// 'spreadsheet',
// );

// await fetch(
// 'https://js.syncfusion.com/demos/ejservices/data/Spreadsheet/LargeData.xlsx',
// ) // fetch the remote url
// .then(response => {
// response.blob().then(fileBlob => {
// // convert the excel file to blob
// const file = new File([fileBlob], 'Sample.xlsx'); // convert the blob into file
// spreadsheet.open({ file: file }); // open the file into Spreadsheet
// });
// });
// };

return (
<div className={classes.parent}>
<SpreadsheetComponent
ref={spreadsheet}
openUrl="https://ej2services.syncfusion.com/production/web-services/api/spreadsheet/open"
created={onCreated}
allowEditing={false} // disables editing of the spreadsheet
allowDelete={false} // disables deleting of any contents in the spreadsheet
showFormulaBar={false} // hides the formula bar
showRibbon={false} // hides the menu bar
enableContextMenu={false} // this hides the right click menu on a cell in the spreadsheet
enableKeyboardShortcut={false} // disables keyboard shortcuts inside the spreadsheet, e.g. Cmd + C (copy)
/>
div>
);
};

export default SpreadsheetViewer;



SP Sangeetha Priya Murugan Syncfusion Team August 29, 2022 07:49 AM UTC

Hi Keith,


If you need to perform open/save action in spreadsheet, you need to provide the open server action link in openUrl property. For more details regarding open/save feature please refer the below link.


https://ej2.syncfusion.com/react/documentation/spreadsheet/open-save/


And for demo purpose we have published our web service open/save action and mentioned in our demo site. You can also use this demo url in your end or else you can use local service for open/save action.
And we have published our API services in the GitHub location, for more details please refer the below links.


Service sample Location: https://github.com/SyncfusionExamples/EJ2-Spreadsheet-WebServices/


For local service creation, please refer the below link.


https://www.syncfusion.com/kb/13200/how-to-remove-trial-version-tab-created-in-spreadsheet


If the spreadsheet instance properly available in your ref variable, you can use that instance or else you can get the instance using our getComponent method. Based on your comfort you can get the instance.


Could you please check the above links and get back to us, if you need any further assistance on this.


Regards,

Sangeetha M



Loader.
Up arrow icon