How To
Use React
Integrating @rustors/react hooks, provider, and overlay components.
Use React
The @rustors/react package provides declarative React primitives: <RustoProvider />, useOcr(), <OcrOverlay />, and <OcrDropzone />.
Installation
npm install @rustors/react @rustors/web @rustors/model-ppocrv6-tiny
# or
yarn add @rustors/react @rustors/web @rustors/model-ppocrv6-tiny
# or
pnpm add @rustors/react @rustors/web @rustors/model-ppocrv6-tiny
Setup Provider
Wrap your application in RustoProvider to manage engine lifecycle and model setup. You can supply models either from local assets or via the jsDelivr CDN:
import React from 'react';
import { RustoProvider } from '@rustors/react';
import { getModelUrls } from '@rustors/model-ppocrv6-tiny';
// Option A: Local assets hosted in public/ folder
// const modelUrls = getModelUrls('/models/ppocrv6-tiny');
// Option B: Hosted directly via jsDelivr CDN (zero local asset management)
const modelUrls = getModelUrls('https://cdn.jsdelivr.net/npm/@rustors/model-ppocrv6-tiny');
export function App() {
return (
<RustoProvider
config={{
preset: 'ppv6',
wasmUrl: 'https://cdn.jsdelivr.net/npm/@rustors/web/dist/wasm/rusto_rten_wasm_bg.wasm',
models: {
detection: modelUrls.detection,
recognition: modelUrls.recognition,
dictionary: modelUrls.dictionary,
},
}}
>
<OcrScanner />
</RustoProvider>
);
}
Scanning with useOcr and <OcrOverlay />
import React, { useState } from 'react';
import { useOcr, OcrOverlay, OcrDropzone } from '@rustors/react';
export function OcrScanner() {
const [imageSrc, setImageSrc] = useState<string | null>(null);
const { detect, results, isProcessing } = useOcr();
const handleFileSelect = async (file: File) => {
setImageSrc(URL.createObjectURL(file));
await detect(file);
};
return (
<div>
<OcrDropzone onFileSelect={handleFileSelect} />
{isProcessing && <p>Scanning document...</p>}
{imageSrc && results.length > 0 && (
<OcrOverlay
imageSrc={imageSrc}
results={results}
onItemClick={(item) => console.log('Clicked box:', item.text)}
/>
)}
</div>
);
}
Content Security Policy (CSP) Troubleshooting
When building React or Next.js applications in enterprise environments with strict CSP headers, ensure these rules are added:
Content-Security-Policy:
script-src 'self' 'wasm-unsafe-eval' https://cdn.jsdelivr.net;
connect-src 'self' https://cdn.jsdelivr.net blob:;
worker-src 'self' blob:;
img-src 'self' data: blob:;
- If you see
EvalError: Refused to compile or instantiate WebAssembly module, add'wasm-unsafe-eval'toscript-src. - If model assets fail to download from jsDelivr, add
https://cdn.jsdelivr.nettoconnect-src. - If worker instantiation throws a
SecurityError, addworker-src 'self' blob:.