# React ⚛

Our `CardScanView` react component makes it easy to add insurance card scanning and eligibility verification to any web application in **5 minutes or less.**

![](https://423317997-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MYkGp0C8rvjnJYLAI_u%2Fuploads%2FV3Dve4VF7hlLVWVcnppn%2Fcardscan.gif?alt=media\&token=bf8c1781-9470-47b7-a26c-0f551b9cfac9)

### Installation

```
$ npm i @cardscan.ai/insurance-cardscan-react
$ yarn add @cardscan.ai/insurance-cardscan-react
```

### Usage

Import the library widget and model into your project files:

```javascript
import { CardScanView, CardScanModel } from "@cardscan.ai/insurance-cardscan-react";
```

You can **optionally** add the API client for more custom applications.

```javascript
import { CardScanApi } from "@cardscan.ai/cardscan-client";
```

### Basic Example

```jsx
import React from "react";
import { render } from "react-dom";
import { CardScanView, CardScanModel } from "@cardscan.ai/insurance-cardscan-react";

function onSuccess(card: any) {
  console.log("New Card: ", card);
}

function onError(error) {
  console.error('Error occurred: ', error);
}

// See Authentication on where to get this sessionToken.
const sessionToken = 'JWT_TOKEN'

// Initializes and warms the model. See CardScanModel for more info.
useEffect(() => {
  CardScanModel.warm();
}, []);

// Render CardScanView
function App() {
  return (
    <div className="App">
      <div className="CardScanContainer">
        <CardScanView
          live={false}
          sessionToken={sessionToken}
          onSuccess={onSuccess}
          onError={onError}
        />
      </div>
    </div>
  );
}

const rootElement = document.getElementById('root');
render(<App />, rootElement);

```

### Compatibility

* **Node Versions**: 14, 16, 18
* **React Versions**: >=17.0.2, 18.2.0+
* **Webpack Versions**: 4.x, 5.x
* **Babel Versions**: 6.x, 7.x

### Peer Dependencies

* **React**: >=17.0.2
* **React-DOM**: >=17.0.2

## Configuration

### Available Props

```jsx
<CardScanView
  // Required
  live={false}
  sessionToken={token}
  onSuccess={onSuccess}

  // Recommneded
  onCancel={onCancel}
  onError={onError}
  onProgress={onProgress}
  
  // Eligibility
  eligibility={eligibility}
  onEligibilitySuccess={eligibilitySuccess}
  onEligibilityError={eligibilityError}
  
  // Camera Options
  cameraOptions={cameraOptions}
  
  // Optional
  backsideSupport={scanBackside}
  onRetry={onRetry}
  cameraPermissionModalConfig={cameraPermissionModalConfig}
  webToMobileHandoffConfig={webToMobileHandoffConfig}

  // UI Customization
  messages={messages}
  successIndicator={successIndicator}
  errorIndicator={errorIndicator}
  closeButton={closeButton}
/>
```

### **Main Props**

<table><thead><tr><th width="289">Prop</th><th width="112">Required</th><th width="135">Type</th><th>Description</th></tr></thead><tbody><tr><td>live</td><td>false</td><td>Boolean</td><td>Toggle the production or sandbox version. <strong>Default</strong>: false</td></tr><tr><td>sessionToken</td><td>true</td><td>String</td><td>A JWT token for the current user, see <a href="../authentication">Authentication</a></td></tr><tr><td>onSuccess</td><td>true</td><td>Function</td><td>Called on successful scan. The first argument is the scanned card.</td></tr><tr><td>onCancel</td><td>false</td><td>Function</td><td>Triggered when the user cancels the CardScanView UI.</td></tr><tr><td>onError</td><td>false</td><td>Function</td><td>Called when an error is returned by the API or the CardScanView fails to initialize.</td></tr><tr><td>onProgress</td><td>true</td><td>Function</td><td>Progress updates during the card scanning process.</td></tr><tr><td>onRetry</td><td>false</td><td>Function</td><td>Called when a failed scan triggers a retry.</td></tr><tr><td>fullScreen</td><td>false</td><td>Boolean</td><td>Toggles the widget between full viewport coverage and a 16:9 aspect ratio within the parent container's width.<br><strong>Default:</strong> true</td></tr><tr><td>backsideSupport</td><td>false</td><td>Boolean</td><td>Enable scanning of the front and back side of the card.<br><strong>Default</strong>: false</td></tr><tr><td>eligibility</td><td>false</td><td>object</td><td>Request payload for the optional post-scan eligibility verification. See: <a data-mention href="../advanced-features/eligibility-verification">eligibility-verification</a></td></tr><tr><td>onEligibilitySuccess</td><td>false</td><td>Function</td><td>Called on successful eligibility request. The eligibility response is pass as an argument.</td></tr><tr><td>onEligibilityError</td><td>false</td><td>Function</td><td>Called when an error is returned by the eligibility API.</td></tr><tr><td>cameraPermissionModalConfig</td><td>false</td><td>object</td><td>The <a href="#camerapermissionmodalconfig"><code>cameraPermissionModalConfig</code></a> object allows customization of the Camera Permission Modal in the application. It provides the flexibility to set custom texts for various parts of the modal, enhancing the user experience by providing clear and relevant information.<br>Default :<code>{ enabled: true }</code></td></tr><tr><td>webToMobileHandoffConfig</td><td>false</td><td>object</td><td>Enables seamless handoff from desktop to mobile when errors are encountered. See: <a data-mention href="../advanced-features/web-to-mobile-handoff">web-to-mobile-handoff</a></td></tr><tr><td>cameraOptions</td><td>false</td><td>object</td><td>Configures the camera's orientation during scanning.</td></tr></tbody></table>

## UI/UX Customization

The react widget is designed to be highly customizable. Please see the [#customization](#customization "mention") section of UI Components to adjust these elements to match your application's branding and theme:

[customization](https://docs.cardscan.ai/ui-components/customization "mention")

{% hint style="info" %}
**Note:** All UI/UX Props are optional
{% endhint %}

<table><thead><tr><th width="313.3333333333333">Prop</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>messages</td><td>Object</td><td>Customize the text displayed by the UI.</td></tr><tr><td>successIndicator</td><td>ReactNode</td><td>Replace the success indicator with a custom react component.</td></tr><tr><td>errorIndicator</td><td>ReactNode</td><td>Replace the error indicator with a custom react component.</td></tr><tr><td>closeButton</td><td>ReactNode</td><td>Replace the close button with a custom react component.</td></tr></tbody></table>

{% hint style="success" %}
**Note:** Additional UI elements can be modified using CSS
{% endhint %}

## Callbacks

### onSuccess Callback

The `onSuccess` prop allows you to execute a custom function when the card scanning process is completed successfully. This function receives the scanned card data as an argument.

#### Usage

To use the `onSuccess` prop, pass a function that receives the scanned card data:

```jsx
const handleCardScanSuccess = (cardData) => {
  console.log('Card scanned successfully:', cardData);
};

<CardScanView
  sessionToken={token}
  onSuccess={handleCardScanSuccess}
/>
```

In this example, the `handleCardScanSuccess` function logs the scanned card data to the console when the scanning process is completed successfully.

### onError Callback

The `onError` prop allows you to execute a custom function when there's a failure during the card scanning process. This function receives an error object as an argument.

#### Usage

To use the `onError` prop, pass a function that receives the error object:

```jsx
const handleCardScanError = (error: CardScanError) => {
  console.error('Scanning failed:', error);
};

<CardScanView
  sessionToken={token}
  onSuccess={cardScanSuccess}
  onError={handleCardScanError}
/>
```

In this example, the `handleCardScanError` function logs the error object to the console when a scanning failure occurs.

By using the `onSuccess` and `onError` props, you can handle successful and failed scanning events, allowing you to implement custom actions or display appropriate messages to the user.

{% hint style="info" %}
You can find examples of the[#error-screens](#error-screens "mention") at the bottom of this document
{% endhint %}

Possible errors returned to the `onError` callback.

```typescript
type CardScanError = {
  message: string;
  type: string;
  code: number;
  isCardScanError: boolean;
};
```

<table><thead><tr><th width="235.66666666666666">Error Type</th><th>Error Code</th><th>Error Message</th></tr></thead><tbody><tr><td>VideoError</td><td>670</td><td>Various system errors of <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia">getUserMedia</a>(), including: “Permission Denied” and “Camera not found”</td></tr><tr><td>VideoError</td><td>675</td><td>Various system errors of <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play">HTMLMediaElement.play()</a>, including: “Permission Denied” and “The element has no supported sources.”</td></tr><tr><td>VideoError</td><td>676</td><td>Any and all other system related video capture &#x26; canvas capture errors.</td></tr><tr><td>WSError</td><td>640</td><td>“No websocket found - critical failure”</td></tr><tr><td>WSError</td><td>642</td><td>“Unknown error from websocket”</td></tr><tr><td>WSError</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code">1002-1003, 1007-1015</a></td><td>“The connection was closed abnormally”</td></tr><tr><td>ResponseError</td><td>HTTP Codes</td><td>Various HTTP errors returned from XMLHttpRequest and the CardScan.ai backend.</td></tr><tr><td>RequestError</td><td>Various</td><td>Various HTTP errors returned from Axios and XMLHttpRequest.</td></tr><tr><td>Unknown</td><td>606</td><td>Possible Axios setup errors, websocket setup errors, etc.</td></tr></tbody></table>

### onCancel Callback

The `onCancel` prop enables you to execute a custom function when the user cancels the card scanning process. This can be useful for tracking user behavior, navigating to a different part of the application, or displaying an appropriate message.

#### Usage

To use the `onCancel` prop, pass a function that will be executed when the user cancels the scanning process:

```jsx
import React, { useState } from 'react';
import {CardScanView} from "@cardscan.ai/insurance-cardscan-react";

const App = () => {
  const [showCardScanView, setShowCardScanView] = useState(true);

  return (
    <div>
      {showCardScanView && (
        <CardScanView
          sessionToken={token}
          onSuccess={cardScanSuccess}
          onError={cardScanError}
          onCancel={() => setShowCardScanView(false)}
        />
      )}
    </div>
  );
};

export default App;

```

In this example, we initialize the `showCardScanView` state variable to `true`. Then, we conditionally render the `CardScanView` component based on the value of `showCardScanView`. We then use the `onCancel` prop to set the `showCardScanView` state variable to `false` when the user cancels the scanning process.

### onRetry Callback

The `onRetry` prop allows you to execute a custom function when a retry is triggered due to a scanning failure.

#### Usage

To use the `onRetry` prop, pass a function that receives the retry event as an argument:

```jsx
const handleRetry = (event) => {
  console.log('Retry triggered:', event);
};

<CardScanView
  sessionToken={token}
  onSuccess={cardScanSuccess}
  onRetry={handleRetry}
/>
```

In this example, the `handleRetry` function logs the retry event to the console when a retry is triggered.

### onProgress Callback

The `onProgress` prop allows you to execute a custom function to report progress during the scanning process.

#### Usage

```jsx
const handleProgress = (progress) => {
  console.log(`Card ID: ${progress.cardId} - Scan Count: ${progress.scanCount} - Card State: ${progress.cardState}`);
};

<CardScanView
  sessionToken={token}
  onSuccess={cardScanSuccess}
  onProgress={handleProgress}
/>
```

In this example, the `handleProgress` function logs the progress during a live scanning operation. When `backsideSupport` is enabled the scan counter will reset to zero when the card is flipped to scan the back side.

{% hint style="info" %}
For the majority of live scanning scenarios, the **scanning will be completed within 2-3 scans.** In situations with low light or occluded card elements, the scan count can go as high as 12.
{% endhint %}

## Additional Features

### Eligibility Verification

Eligibility Verification is crucial in healthcare for confirming a patient's insurance coverage and benefits before services are provided, streamlining billing and enhancing patient care.

By providing subscriber and provider details through our React component, users can initiate the verification process effortlessly. The widget offers real-time feedback with success and error callbacks, simplifying integration into your application's UI.

See [eligibility-verification](https://docs.cardscan.ai/advanced-features/eligibility-verification "mention") for more details.

### Embedding

The `fullScreen` prop controls the sizing behavior of the widget. When set to `true`, the widget expands to fill the entire viewport, providing a full-screen experience. Setting it to `false` keeps the widget within the width of its parent container, maintaining a 16:9 aspect ratio. This property ensures that the widget can be embedded in various layouts while preserving its visual integrity.

**Example:**

```jsx
<div className="scanner-container" style={{ width: "800px" }}>
    <CardScanView 
        fullScreen={false}
        sessionToken={token}
        onSuccess={cardScanSuccess}
        onCancel={cardScanCancel}
        onError={cardScanError}
    />
</div>
```

### Camera Options

Camera Configuration allow developers to preset the camera's view orientation for specific installation scenarios, such as mirrored cameras or kiosks. These settings ensure the camera view is correctly aligned and oriented during the initial setup of the application:

* `flipHorizontal`: Enables horizontal flipping of camera view, reversing the left to right sides of the image (aka mirrored)
* `flipVertical`: Enabled vertical flipping of camera view, swapping the top and bottom of the image when the camera or document is upside down.

```jsx
<CardScanView 
    sessionToken={token}
    onSuccess={cardScanSuccess}
    cameraOptions={{
        flipHorizontal: false,
        flipVertical: true
    }}
/>

```

### Camera Permissions Modal

The camera permission modal is designed to handle all possible scenarios where users may refuse permission for their camera device. It serves to guide users through the steps needed to resolve a rejected permission request, whether the user manually declined access or if the device automatically blocked the permission. This ensures that users are informed and can take the necessary actions to enable camera access.

For further details, please visit the dedicated page:

{% content-ref url="../advanced-features/camera-permission-modal" %}
[camera-permission-modal](https://docs.cardscan.ai/advanced-features/camera-permission-modal)
{% endcontent-ref %}

### CardScanModel

The `CardScanModel` class is designed to load and "warm" the TensorFlowJS model used during live scanning to detect insurance cards. Properly warming the model ensures it is ready for immediate use in the scanning process.

#### Importing the class

To utilize the `CardScanModel` in your project, import it as follows:

```tsx
import { CardScanModel } from "@cardscan.ai/insurance-cardscan-react";
```

#### **Warming the Model**

While importing the class and warming the model are optional, doing so will result in faster widget initialization and happier users. To warm the model, call the `warm` method once during the component mount. This initializes the model loading and warming process, making it ready for scanning.

```tsx
CardScanModel.warm();
```

**Custom Model Path**

Optionally, you can provide a custom model path to a local version of the model file or to a CDN that you control. Ensure the model files are included in your build folder. If the model cannot be loaded from the provided path, it will default to fetching the model from the CDN.

```tsx
CardScanModel.warm("path/to/model.json");
```

#### Model Assets

To include the model assets in your build system, configure your bundler (such as Webpack, Rollup, or a similar tool) to import all files from the `assets/model-tfjs` folder in the npm package. The exact configuration will depend on your specific build setup and requirements.

{% hint style="info" %}
Please reach out to support if you need help configuring your build system.
{% endhint %}

## Error Screens

#### **Setup Failure**

<figure><img src="https://423317997-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MYkGp0C8rvjnJYLAI_u%2Fuploads%2F6MGCQCwBO0TIcEg4FRRm%2Fsetup_failure.png?alt=media&#x26;token=14ab925d-beeb-481c-977d-5bda50c892b3" alt=""><figcaption></figcaption></figure>

This screen will be shown on setup connection failure (websocket or initial REST API call), network error, auth failure (invalid or expired token), and camera error (without webToMobileHandOff or enableCameraPermissionModal enabled).

#### **Scan Failure**

<figure><img src="https://423317997-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MYkGp0C8rvjnJYLAI_u%2Fuploads%2F5JW9YcpGbEu4mtR4VHjn%2Fscanning_failed.png?alt=media&#x26;token=e2f908f6-3a17-43a5-baa6-dc1950f13011" alt=""><figcaption></figcaption></figure>

This screen will be shown on direct upload of an invalid image (i.e. a photo of a cat) or when all 12+ scan attempts have been exhausted because of poor input quality or complete backend failure.

{% hint style="info" %}
**Are we missing something?** Please let us know and we would be happy to add it. Contact [support](mailto:support@cardscan.ai).
{% endhint %}
