Monday, December 6, 2021

React.js, download pdf



Handle pdf download in React.js

                   <div className="formRow float-right-no-margin">
                        {this.props && this.props.file && this.props.file.length > 0 && (
                            <Button variant="primary" onClick={handlePdfDownload}>
                                Download
                            </Button>
                        )}
                        &nbsp;&nbsp;
                        <Button variant="secondary" onClick={this.props.handlePreviewClose}>
                            Close
                        </Button>
                    </div>
 

        const handlePdfDownload = () => {
            // Insert a link that allows the user to download the PDF file
            var link = document.createElement('a');
            link.innerHTML = 'Download PDF file';
            link.download = this.props.fileName;
            link.href = this.props.file;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        };

//hide Modal

   handlePreviewClose = () => {
        this.setState({ showPreview: false, pageNumber: 1 })
    };

 

Friday, December 3, 2021

axios handle blob type data




Reference:

https://stackoverflow.com/questions/60454048/how-does-axios-handle-blob-vs-arraybuffer-as-responsetype 

axios:

https://www.npmjs.com/package/axios 

 

'blob' is a "browser only" option for image, pdf etc

Example:

function fetchAs( type ) {
  return axios( {
    method: 'get',
    url: 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png',
    responseType: type
  } );
}
function loadImage( data, type ) {
  // we can all pass them to the Blob constructor directly
  const new_blob = new Blob( [ data ], { type: 'image/jpg' } );
  // with blob: URI, the browser will try to load 'data' as-is
  const url = URL.createObjectURL( new_blob );
  
  img = document.getElementById( type + '_img' );
  img.src = url;
  return new Promise( (res, rej) => { 
    img.onload = e => res(img);
    img.onerror = rej;
  } );
} 
[
  'json', // will fail
  'text', // will fail
  'arraybuffer',
  'blob'
].forEach( type =>
  fetchAs( type )
   .then( resp => loadImage( resp.data, type ) )
   .then( img => console.log( type, 'loaded' ) )
   .catch( err => console.error( type, 'failed' ) )
);
 
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<figure>
  <figcaption>json</figcaption>
  <img id="json_img">
</figure>
<figure>
  <figcaption>text</figcaption>
  <img id="text_img">
</figure>
<figure>
  <figcaption>arraybuffer</figcaption>
  <img id="arraybuffer_img">
</figure>
<figure>
  <figcaption>blob</figcaption>
  <img id="blob_img">
</figure>   

 

react-pdf, display pdf in react.js



Reference: 

https://www.npmjs.com/package/react-pdf

Example 1

import React, { useState } from 'react';
import { Document, Page } from 'react-pdf';

function MyApp() {
  const [numPages, setNumPages] = useState(null);
  const [pageNumber, setPageNumber] = useState(1);

  function onDocumentLoadSuccess({ numPages }) {
    setNumPages(numPages);
  }

  return (
    <div>
      <Document
        file="somefile.pdf"
        onLoadSuccess={onDocumentLoadSuccess}
      >
        <Page pageNumber={pageNumber} />
      </Document>
      <p>Page {pageNumber} of {numPages}</p>
    </div>
  );

 Example 2

                            <div>
                                <Document
                                    file={this.props.file}
                                    onLoadSuccess={this.props.onDocumentLoadSuccess}
                                >
                                    <Page pageNumber={this.props.pageNumber} />
                                </Document>
                                <p>
                                    {this.props.pageNumber > 1 && (
                                        <a onClick={() => this.props.setPageNumber(this.props.pageNumber - 1)} >
                                            &lt;
                                        </a>
                                    )}
                                    &nbsp;&nbsp;Page {this.props.pageNumber} of {this.props.numPages}&nbsp;&nbsp;
                                    {this.props.pageNumber < this.props.numPages && (
                                        <a onClick={() => this.props.setPageNumber(this.props.pageNumber + 1)}
                                            disabled={this.props.pageNumber < this.props.numPages ? '' : 'disabled'}>
                                            &gt;
                                        </a>
                                    )}
                                </p>
 

                            </div>

File can be from:

          this.setState({

            file: 'data:application/pdf;base64,' + encodeURI(response.data),
        })

Wednesday, December 1, 2021

async in react.js




All react JS is asynchronous.

it provides a declarative API to perform any REST API calls using a single React component 

Example

     componentDidMount() {
        this.getData();
    }
    async getData() {
      this.setState({loading: true});
        axios
            .get("/access_control/access/getAll")
            .then(response => {
                this.setState({
                    data: response.data,
                    loading: false
                })
            })
            .catch(error => {
                console.error(
                    'There has been a probelm with an axios operation:',
                    error
                );
                this.setState({ifSuccess: false, msg: 'There has been a probelm with retriving module list.', loading: false});
            });
    }

Use componentDidMount in React.js




Reference:

https://reactjs.org/tutorial/tutorial.html

componentDidMount is called exactly once and when The component has been initialized. The component has bind with the container element and rendered successfully. All the properties and initial states has been initialized. You can now call setState and other component function on this component, manipulate it and so on. Simply it is the starting point for you to interact with it.

componentDidMount is useful  for AJAX requests. 

componentDidMount() executes after the render() at first execution. After that it executes before the render() according to React Lifecycle.

React.js: pass variables in different components



In React.js

    setSearchYear = (data) => {
        this.setState({searchYear: data})
    }

              <ApplicationList
                 setSearchYear={this.setSearchYear}
                />

setSearchYear is passed to component ApplicationList, ApplicationList.js

                                   <div className="col-2 text-left form-group">
                                        <Select
                                            id="searchYear"
                                            name="searchYear"
                                            closeMenuOnSelect={true}
                                            components={this.props.animatedComponents}
                                            onChange={value => this.props.setSearchYear( value.value )}
                                            options={this.props.yearList}
                                            defaultValue={[{ label: 'All Fiscal Years', value: 0 }]}
                                        />
                                    </div>