How to Add an AI Agent to Your React App in 10 Minutes

InAppAI Team
4 min read
How to Add an AI Agent to Your React App in 10 Minutes

This tutorial demonstrates integrating an AI agent into React applications. Unlike chatbots that answer questions, these agents understand app state and can take actions—creating records, updating data, and triggering workflows.

What You’ll Learn

  1. Installing the component
  2. Adding it to your app with a display mode
  3. Providing context about your app’s state
  4. Defining tools the agent can execute

Installation

npm install @inappai/react

Core Component Structure

The <InAppAI> component handles the chat interface and agent communication:

import { useState } from 'react';
import { InAppAI, Message } from '@inappai/react';

function App() {
  const [messages, setMessages] = useState<Message[]>([]);

  return (
    <div>
      <InAppAI
        agentId="your-agent-id"
        messages={messages}
        onMessagesChange={setMessages}
        displayMode="popup"
      />
    </div>
  );
}

Display Modes

ModePurpose
popupFloating button with chat window
sidebarFixed side panel
inlineEmbedded in layout
fullscreenFull viewport takeover
modalCentered overlay
hiddenProgrammatic control only

Context Function

Context provides the agent with current app state. The function-based approach ensures fresh data after each agent action:

context={() => ({
  currentUser: { name: 'Alice', role: 'admin' },
  currentPage: 'dashboard',
  selectedItems: selectedItems,
})}

Tool Definition

Tools enable agent actions. Each tool requires:

  • name: identifier
  • description: usage context
  • parameters: input schema (JSON Schema format)
  • handler: execution function

Example search tool:

{
  name: 'search',
  description: 'Search for items by keyword',
  parameters: {
    type: 'object',
    properties: {
      query: { type: 'string', description: 'Search term' },
    },
    required: ['query'],
  },
  handler: async ({ query }) => {
    const results = items.filter(item =>
      item.name.toLowerCase().includes(query.toLowerCase())
    );
    return { results, count: results.length };
  },
}

Task Manager Example

Here’s a complete task management application with tools for creating, listing, completing, and deleting tasks:

import { useState } from 'react';
import { InAppAI, Message, Tool } from '@inappai/react';

interface Task {
  id: string;
  title: string;
  priority: 'low' | 'medium' | 'high';
  status: 'pending' | 'completed';
}

function TaskManager() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [tasks, setTasks] = useState<Task[]>([]);

  const tools: Tool[] = [
    {
      name: 'createTask',
      description: 'Create a new task with a title and priority',
      parameters: {
        type: 'object',
        properties: {
          title: { type: 'string', description: 'Task title' },
          priority: {
            type: 'string',
            enum: ['low', 'medium', 'high'],
            description: 'Task priority level'
          },
        },
        required: ['title', 'priority'],
      },
      handler: async ({ title, priority }) => {
        const newTask: Task = {
          id: crypto.randomUUID(),
          title,
          priority,
          status: 'pending',
        };
        setTasks(prev => [...prev, newTask]);
        return { success: true, task: newTask };
      },
    },
    {
      name: 'listTasks',
      description: 'List all tasks, optionally filtered by status or priority',
      parameters: {
        type: 'object',
        properties: {
          status: { type: 'string', enum: ['pending', 'completed'] },
          priority: { type: 'string', enum: ['low', 'medium', 'high'] },
        },
      },
      handler: async ({ status, priority }) => {
        let filtered = tasks;
        if (status) filtered = filtered.filter(t => t.status === status);
        if (priority) filtered = filtered.filter(t => t.priority === priority);
        return { tasks: filtered, count: filtered.length };
      },
    },
    {
      name: 'completeTask',
      description: 'Mark a task as completed',
      parameters: {
        type: 'object',
        properties: {
          taskId: { type: 'string', description: 'The task ID to complete' },
        },
        required: ['taskId'],
      },
      handler: async ({ taskId }) => {
        setTasks(prev => prev.map(t =>
          t.id === taskId ? { ...t, status: 'completed' } : t
        ));
        return { success: true };
      },
    },
    {
      name: 'deleteTask',
      description: 'Delete a task by ID',
      parameters: {
        type: 'object',
        properties: {
          taskId: { type: 'string', description: 'The task ID to delete' },
        },
        required: ['taskId'],
      },
      handler: async ({ taskId }) => {
        setTasks(prev => prev.filter(t => t.id !== taskId));
        return { success: true };
      },
    },
  ];

  return (
    <div>
      <h1>Task Manager</h1>
      <ul>
        {tasks.map(task => (
          <li key={task.id}>
            {task.title} - {task.priority} - {task.status}
          </li>
        ))}
      </ul>
      <InAppAI
        agentId="your-agent-id"
        messages={messages}
        onMessagesChange={setMessages}
        tools={tools}
        context={() => ({ tasks, taskCount: tasks.length })}
        displayMode="popup"
      />
    </div>
  );
}

Advanced Features

Knowledge Base (RAG)

The system supports documentation integration through the InAppAI dashboard, enabling semantic search across:

  • Documentation sites
  • Blog posts
  • GitHub repositories

Backend Configuration

The managed backend handles AI provider routing, rate limiting, usage tracking, and CORS settings. User identification uses the optional authToken prop.

Use Case Applications

These patterns apply to various applications:

  • CRM systems
  • Admin dashboards
  • E-commerce platforms
  • Project management tools
  • Support portals

Get Started

Try the demo: react-demo.inappai.com

Read the docs: inappai.com/docs

Star on GitHub: github.com/inappai/react

Ready to Add AI to Your Application?

Join developers building intelligent applications with InAppAI