Skip to main content

React SDK

React components for seamlessly integrating Char AI into React applications.

Installation

npm install @char-ai/react

Quick Start

import { CharWidget } from '@char-ai/react';

function App() {
  return (
    <CharWidget
      apiKey="char_sk_live_..."
      theme="light"
    />
  );
}

Components

<CharWidget />

The main chat widget component:
<CharWidget
  apiKey="char_sk_live_..."
  theme="dark"
  position="bottom-right"
  user={{
    id: 'user_123',
    email: '[email protected]'
  }}
  onOpen={() => console.log('Opened')}
  onClose={() => console.log('Closed')}
  onMessage={(msg) => console.log(msg)}
/>

Props

PropTypeDefaultDescription
apiKeystringrequiredYour site API key
theme'light' | 'dark' | 'auto''auto'Color theme
mode'embedded' | 'floating''floating'Display mode
position'bottom-right' | 'bottom-left''bottom-right'Position
userUserundefinedUser identification
colorsColors{}Custom colors
defaultOpenbooleanfalseStart widget open

Event Props

PropTypeDescription
onOpen() => voidCalled when widget opens
onClose() => voidCalled when widget closes
onMessage(message: Message) => voidCalled on new message
onError(error: Error) => voidCalled on error

<CharProvider />

Context provider for sharing configuration:
import { CharProvider, CharWidget, useChar } from '@char-ai/react';

function App() {
  return (
    <CharProvider apiKey="char_sk_live_...">
      <Layout />
    </CharProvider>
  );
}

function Layout() {
  const { open, close, isOpen } = useChar();

  return (
    <div>
      <button onClick={open}>Open Chat</button>
      <CharWidget />
    </div>
  );
}

Hooks

useChar()

Access widget state and methods:
import { useChar } from '@char-ai/react';

function ChatButton() {
  const { open, close, toggle, isOpen, sendMessage } = useChar();

  return (
    <button onClick={toggle}>
      {isOpen ? 'Close' : 'Open'} Chat
    </button>
  );
}

useMessages()

Access message history:
import { useMessages } from '@char-ai/react';

function MessageList() {
  const { messages, isLoading } = useMessages();

  if (isLoading) return <div>Loading...</div>;

  return (
    <ul>
      {messages.map((msg) => (
        <li key={msg.id}>{msg.content}</li>
      ))}
    </ul>
  );
}

TypeScript

Full TypeScript support:
import { CharWidget, User, Message, Colors } from '@char-ai/react';

interface Props {
  currentUser: User;
}

function Chat({ currentUser }: Props) {
  const handleMessage = (message: Message) => {
    console.log(message.content);
  };

  return (
    <CharWidget
      apiKey="char_sk_live_..."
      user={currentUser}
      onMessage={handleMessage}
    />
  );
}