Verba LogoDocs

React Integration

To integrate the Verba AI chat widget with React, you can create a custom ChatWidget component that manages the lifecycle of the widget instance.

NOTE: targetElement is optional. If not provided, a floating widget will appear by default in the bottom-right corner.

tsx
'use client'

import React, { useEffect, useRef } from 'react'
import { VerbaChat } from '@verba-ai/chat-sdk'

interface ChatWidgetProps {
    token?: string
}

const tagId = import.meta.env.VITE_EMBED

const ChatWidget: React.FC<ChatWidgetProps> = ({ token }) => {
    const chatRef = useRef<VerbaChat | null>(null)

    useEffect(() => {
        // 1. Initialize the widget
        chatRef.current = new VerbaChat({
            tagId,
            token,
            targetElement: '#verba-chat-container',
            theme: 'light',
            withThreadList: true,
        })

        // 2. Mount the widget
        chatRef.current.init()

        // 3. Clean up the widget on unmount
        return () => {
            if (chatRef.current) {
                chatRef.current.destroy()
                chatRef.current = null
            }
        }
    }, [tagId, token])

    return (
        <div
            id="verba-chat-container"
            style={{
                width: '100%',
                height: '600px',
                border: '1px solid #eee',
                borderRadius: '8px',
            }}
        />
    )
}

export default ChatWidget