React Usage Guide
This guide provides detailed instructions for integrating and using the InsightEmbed widget in React applications.
Installation
InsightEmbed offers an official React component that makes integration seamless. Install it using npm or yarn:
# Using npm
npm install @insightembed/react
# Using yarn
yarn add @insightembed/reactBasic Usage
Once installed, you can import and use the InsightEmbed component in your React application:
import React from 'react';
import { InsightEmbed } from '@insightembed/react';
function App() {
return (
<div className="App">
<h1>My React Application</h1>
<InsightEmbed apiKey="YOUR_WIDGET_API_KEY" />
</div>
);
}
export default App;Configuration Options
The React component accepts all the same configuration options as the standard JavaScript widget:
import React from 'react';
import { InsightEmbed } from '@insightembed/react';
function App() {
const widgetConfig = {
apiKey: 'YOUR_WIDGET_API_KEY',
theme: {
primaryColor: '#0F766E',
backgroundColor: '#F8FAFC',
textColor: '#334155'
},
position: {
anchor: 'bottom-right',
horizontalOffset: 20,
verticalOffset: 20
},
branding: {
buttonLabel: 'Analyze',
panelTitle: 'Content Analysis'
}
};
return (
<div className="App">
<h1>My React Application</h1>
<InsightEmbed {...widgetConfig} />
</div>
);
}
export default App;Inline Widget Placement
You can embed the widget inline within your React components:
import React from 'react';
import { InsightEmbed } from '@insightembed/react';
function BlogPost() {
return (
<article className="blog-post">
<h1>Understanding AI in Modern Applications</h1>
<p>This article explores how AI is transforming web applications...</p>
<div className="analysis-widget">
<h3>Analyze This Content</h3>
<InsightEmbed
apiKey="YOUR_WIDGET_API_KEY"
position={{
type: 'inline',
container: '.analysis-widget'
}}
/>
</div>
<p>As we've seen, the integration of AI capabilities...</p>
</article>
);
}
export default BlogPost;Using Hooks
The package provides React hooks for more advanced integration scenarios:
import React, { useState } from 'react';
import { useInsightEmbed } from '@insightembed/react';
function AnalysisComponent() {
const [content, setContent] = useState('');
const [result, setResult] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const { analyze } = useInsightEmbed({
apiKey: 'YOUR_WIDGET_API_KEY',
onInitialized: () => console.log('InsightEmbed initialized'),
onError: (error) => console.error('InsightEmbed error:', error)
});
const handleAnalysis = async () => {
if (!content.trim()) return;
setIsLoading(true);
try {
const analysisResult = await analyze(content);
setResult(analysisResult);
} catch (error) {
console.error('Analysis failed:', error);
} finally {
setIsLoading(false);
}
};
return (
<div className="analysis-component">
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Enter content to analyze"
rows={5}
/>
<button onClick={handleAnalysis} disabled={isLoading}>
{isLoading ? 'Analyzing...' : 'Analyze Content'}
</button>
{result && (
<div className="analysis-result">
<h3>Analysis Result</h3>
<p>{result.analysis}</p>
</div>
)}
</div>
);
}
export default AnalysisComponent;Programmatic Control
You can programmatically control the widget using the component's ref:
import React, { useRef } from 'react';
import { InsightEmbed } from '@insightembed/react';
function ControlledWidget() {
const widgetRef = useRef();
const handleShowWidget = () => {
if (widgetRef.current) {
widgetRef.current.show();
}
};
const handleHideWidget = () => {
if (widgetRef.current) {
widgetRef.current.hide();
}
};
const handleExpandWidget = () => {
if (widgetRef.current) {
widgetRef.current.expand();
}
};
return (
<div>
<div className="widget-controls">
<button onClick={handleShowWidget}>Show Widget</button>
<button onClick={handleHideWidget}>Hide Widget</button>
<button onClick={handleExpandWidget}>Expand Widget</button>
</div>
<InsightEmbed
ref={widgetRef}
apiKey="YOUR_WIDGET_API_KEY"
initiallyVisible={false}
/>
</div>
);
}
export default ControlledWidget;Event Handling
The React component provides event props for handling various widget events:
import React from 'react';
import { InsightEmbed } from '@insightembed/react';
function EventHandlingExample() {
const handleAnalysisComplete = (result) => {
console.log('Analysis completed:', result);
// You can store the result in state, send to analytics, etc.
};
const handleWidgetOpen = () => {
console.log('Widget opened');
};
const handleWidgetClose = () => {
console.log('Widget closed');
};
return (
<div>
<h2>Event Handling Example</h2>
<InsightEmbed
apiKey="YOUR_WIDGET_API_KEY"
onAnalysisComplete={handleAnalysisComplete}
onOpen={handleWidgetOpen}
onClose={handleWidgetClose}
/>
</div>
);
}
export default EventHandlingExample;Context Provider
For more complex applications, you can use the provided context provider to make the widget available throughout your component tree:
// In your root component (e.g., App.js)
import React from 'react';
import { InsightEmbedProvider } from '@insightembed/react';
import MainContent from './MainContent';
function App() {
return (
<InsightEmbedProvider apiKey="YOUR_WIDGET_API_KEY">
<div className="App">
<header>My Application</header>
<MainContent />
<footer>© 2023</footer>
</div>
</InsightEmbedProvider>
);
}
export default App;
// In a child component
import React from 'react';
import { useInsightEmbedContext } from '@insightembed/react';
function AnalysisButton() {
const { analyze, isInitialized } = useInsightEmbedContext();
const handleClick = async () => {
if (!isInitialized) return;
try {
const result = await analyze('Content to analyze');
console.log('Analysis result:', result);
} catch (error) {
console.error('Analysis failed:', error);
}
};
return (
<button onClick={handleClick} disabled={!isInitialized}>
Analyze Sample Content
</button>
);
}
export default AnalysisButton;Server-Side Rendering (SSR)
The InsightEmbed React component is compatible with server-side rendering frameworks like Next.js:
// pages/index.js in a Next.js project
import React from 'react';
import dynamic from 'next/dynamic';
// Import the component dynamically with SSR disabled
const InsightEmbed = dynamic(
() => import('@insightembed/react').then(mod => mod.InsightEmbed),
{ ssr: false }
);
function HomePage() {
return (
<div>
<h1>Welcome to My Next.js Site</h1>
<InsightEmbed apiKey="YOUR_WIDGET_API_KEY" />
</div>
);
}
export default HomePage;TypeScript Support
The package includes TypeScript definitions for all components and hooks:
import React from 'react';
import { InsightEmbed, InsightEmbedProps } from '@insightembed/react';
interface MyComponentProps {
showWidget: boolean;
}
const MyComponent: React.FC<MyComponentProps> = ({ showWidget }) => {
const widgetConfig: InsightEmbedProps = {
apiKey: 'YOUR_WIDGET_API_KEY',
initiallyVisible: showWidget,
theme: {
primaryColor: '#0F766E'
}
};
return (
<div>
<h2>TypeScript Example</h2>
<InsightEmbed {...widgetConfig} />
</div>
);
};
export default MyComponent;Best Practices
API Key Security: Never hardcode your API key in client-side code. Instead, load it from environment variables or a secure backend endpoint.
Conditional Rendering: Consider conditionally rendering the widget based on user preferences or page context.
Performance: The widget is designed to be lightweight, but for optimal performance, consider lazy-loading it only when needed.
Error Handling: Always implement proper error handling for API calls and widget initialization.
Accessibility: Ensure your implementation maintains accessibility standards by providing appropriate ARIA attributes and keyboard navigation.
Troubleshooting
Widget Not Appearing
If the widget doesn't appear:
- Check that your API key is correct
- Verify that the component is actually rendering (add a border or background to see its container)
- Check the browser console for any errors
- Ensure there are no CSS conflicts hiding the widget
SSR Issues
If you encounter issues with server-side rendering:
- Make sure you're using dynamic importing with
{ ssr: false } - Verify that the widget only initializes on the client side
- Use useEffect for any initialization code
TypeScript Errors
If you encounter TypeScript errors:
- Ensure you're using the latest version of the package
- Check that your TypeScript version is compatible (requires TS 4.0+)
- Import types correctly from the package
For more troubleshooting help, see the Common Errors guide.