# React quickstart

Draw a Fin conversation inside your own React chat. Your app keeps its bubbles, composer, layout
and scrolling; `@nearai/financial-agents-react` draws what is Fin's: the agent's replies, its activity, the
approval and question cards, result cards and how each run ended.

The components never fetch. Your server reads Fin with [`@nearai/financial-agents-sdk`](/sdk-quickstart) and
relays the events; the components draw them and report what the user did.

## Before you begin

- **React 19** with `react-dom`, and `@base-ui/react` 1.3 or later.
- **A relay** from your server to the page, such as the
  [server-sent events recipe](/sdk-recipes#relay-a-conversation-to-your-browser).
- **TypeScript 5.4 or later**, if you type-check.

## 1. Install and import the styles

```sh
npm install @nearai/financial-agents-react @base-ui/react
```

Import the stylesheet once, beside your global CSS:

```ts title="app/layout.tsx"
import "@nearai/financial-agents-react/styles.css";
```

It styles nothing outside Fin's blocks: its rules sit in a `fin` cascade layer, and every class
and variable is prefixed. In a Tailwind app, declare the layer order above your Tailwind import:

```css title="app/globals.css"
@layer theme, base, fin, components, utilities;
@import "tailwindcss";
```

## 2. Fold the events

`threadReducer` folds the events your relay sends, exactly as the SDK yields them, into the
thread. It ignores an event it has already seen, so a replay after a reconnect is harmless.

```ts title="use-thread.ts"
import { initialThread, type StreamEvent, threadReducer } from "@nearai/financial-agents-react/model";
import { useEffect, useReducer } from "react";

export function useThread(conversationId: string) {
  const [thread, dispatch] = useReducer(threadReducer, initialThread);
  useEffect(() => {
    const url = `/api/fin/events?conversationId=${encodeURIComponent(conversationId)}`;
    const source = new EventSource(url);
    source.onmessage = (message) => dispatch(JSON.parse(message.data) as StreamEvent);
    return () => source.close();
  }, [conversationId]);
  return thread;
}
```

Give the component that holds a thread `key={conversationId}`, so another conversation starts
from `initialThread`.

## 3. Add the provider

`FinUIProvider` tells Fin's blocks how your app links. It carries no data.

```tsx title="fin-chat.tsx"
import { FinUIProvider } from "@nearai/financial-agents-react";
import type { ReactNode } from "react";

export function FinChat({ children }: { children: ReactNode }) {
  return (
    <FinUIProvider
      link={Link}
      routes={{
        automation: (id) => `/agent/automations/${id}`,
        orders: () => "/agent/orders",
        assets: () => "/agent/wallet",
      }}
    >
      {children}
    </FinUIProvider>
  );
}
```

| Prop | Purpose |
| --- | --- |
| `link` | Your router's link component, such as Next.js's `Link`. Defaults to a plain anchor. |
| `routes` | The agent's pages in your app that cards link to. Unset routes keep near.com's paths. Name `asset` to link every token Fin draws to your page for it. |
| `tokens` | What each token looks like. Defaults to near.com's list; see [Tokens and chains](/tokens-and-chains). |

## 4. Draw the transcript

`transcriptEntries(thread)` lists what to draw, in order. Draw messages your way, the agent's text
with `MessageMarkdown`, and everything else with `FinEntry`:

```tsx title="transcript.tsx"
import {
  ApprovalExpansionProvider,
  type ApprovalHandlers,
  FinEntry,
  MessageMarkdown,
} from "@nearai/financial-agents-react";
import {
  entryKey,
  replyContext,
  type ThreadState,
  transcriptEntries,
} from "@nearai/financial-agents-react/model";
import { useMemo } from "react";

export function Transcript(props: { thread: ThreadState; approvals: ApprovalHandlers }) {
  const { thread, approvals } = props;
  // Recomputed only when the thread changes, so each reply redraws only when its text does.
  const context = useMemo(() => replyContext(thread.items), [thread.items]);
  return (
    <ApprovalExpansionProvider>
      <div role="log" aria-live="polite" className="my-transcript">
        {transcriptEntries(thread).map((entry) => {
          const key = entryKey(entry);
          if (entry.kind === "item" && entry.item.kind === "user")
            return <p key={key} className="my-bubble">{entry.item.text}</p>;
          if (entry.kind === "item" && entry.item.kind === "assistant")
            return <MessageMarkdown key={key} text={entry.item.text} context={context} />;
          return (
            <div key={key} className="my-entry">
              <FinEntry entry={entry} thread={thread} approvals={approvals} />
            </div>
          );
        })}
        {thread.streamingText ? (
          <MessageMarkdown text={thread.streamingText} streaming context={context} />
        ) : null}
      </div>
    </ApprovalExpansionProvider>
  );
}
```

- **An `item` entry** is one thing in the thread: a message (`user`, `assistant`), a trade
  (`tool`), its receipt (`settlement`), a `question`, an `approval`, or a `run` ending.
- **An `activity` entry** folds the tool calls between two parts of a reply into one line, with
  the cards their results draw.
- **`FinEntry`** draws nothing for a message, which is yours, and may draw several blocks: give
  each entry the container and spacing your layout wants.
- **`replyContext`** gives a reply's bolded assets their icon and trend line.
- **Live text** is `thread.streamingText` until the saved reply replaces it; `streaming` draws
  the caret.

## 5. Handle approvals and questions

The approval and question cards report the user's choice through handlers you pass `FinEntry`,
and show the decision in progress while your server sends it:

```ts title="use-approvals.ts"
import type { ApprovalHandlers } from "@nearai/financial-agents-react";
import { useState } from "react";

export function useApprovals(): ApprovalHandlers {
  const [decidingId, setDecidingId] = useState<string | null>(null);
  const [conflicts, setConflicts] = useState<Record<string, string>>({});
  return {
    decidingId,
    conflicts,
    onDecide: async (approvalId, approve) => {
      setDecidingId(approvalId);
      const refusal = await decide(approvalId, approve); // your server approves or denies
      if (refusal) setConflicts((all) => ({ ...all, [approvalId]: refusal }));
      setDecidingId(null);
    },
    onDismissConflict: (approvalId) =>
      setConflicts(({ [approvalId]: _dismissed, ...rest }) => rest),
  };
}
```

Your server sends the decision with `approvals.approve` or `approvals.deny`; an action that moves
money also needs the user's
[wallet signature](/sdk-recipes#money-needs-the-user-s-signature). `QuestionHandlers` work the
same way for `questions`, answered with `questions.answer`.

> [!NOTE]
> The card draws the exact terms of the contract Fin derived, never the model's words. A contract
> this version cannot read offers only Cancel and asks the user to update the app.

## 6. Let the user send feedback on a reply

Under a finished reply `FinEntry` can draw a thumb each way; a thumbs-down also offers a short
fixed list of reasons. Pass `feedback` handlers and it does; leave it out and no thumbs are
drawn. The feedback the user already gave is the run's `feedback`, which your server reads for
the whole thread with one `runs.list({ conversationId })`, and a tap reports the new feedback:

```ts title="use-feedback.ts"
import type { FeedbackHandlers } from "@nearai/financial-agents-react";
import { useState } from "react";

export function useFeedback(initial: FeedbackHandlers["ratings"]): FeedbackHandlers {
  const [ratings, setRatings] = useState(initial);
  const [busyRunIds, setBusyRunIds] = useState<readonly string[]>([]);
  const [errors, setErrors] = useState<Record<string, string>>({});
  return {
    ratings,
    busyRunIds,
    errors,
    onRate: async (runId, feedback) => {
      setBusyRunIds((ids) => [...ids, runId]);
      setErrors(({ [runId]: _cleared, ...rest }) => rest);
      const refusal = await rate(runId, feedback); // your server sends or deletes the feedback
      if (refusal) setErrors((all) => ({ ...all, [runId]: refusal }));
      else setRatings((all) => ({ ...all, [runId]: feedback }));
      setBusyRunIds((ids) => ids.filter((id) => id !== runId));
    },
  };
}
```

Pass it to each entry as `<FinEntry … feedback={feedback} />`. Your server sends feedback with
`runs.sendFeedback`, and `null` (the user tapped the thumb they had chosen) with
`runs.deleteFeedback`. Fin takes feedback on a run that has ended, so the thumbs appear under a
finished or failed reply only, and never under one the user stopped. Several replies can be saving
at once: `busyRunIds` holds each one's thumbs until its own answer lands.

## 7. Offer the next steps

A reply can end with replies the agent suggests sending next. `MessageMarkdown` leaves them out;
offer them under the latest reply with `NextSteps`:

```tsx title="reply.tsx"
import { MessageMarkdown, NextSteps } from "@nearai/financial-agents-react";
import { type ReplyContext, splitReplyNextSteps } from "@nearai/financial-agents-react/model";

export function Reply(props: { text: string; context: ReplyContext; latest: boolean }) {
  const { nextSteps } = splitReplyNextSteps(props.text);
  return (
    <div>
      <MessageMarkdown text={props.text} context={props.context} />
      {props.latest ? <NextSteps steps={nextSteps} onPick={send} /> : null}
    </div>
  );
}
```

## 8. Let the cards carry the facts

When your server starts a run, send `RENDERED_CARDS` as `context.renders`
([recipe](/sdk-recipes#send-a-message)). The agent then leaves receipts, saved automations, the
wallet, limit orders, saved contacts and grids to the cards instead of repeating them in its
reply. The contacts card links to your own contacts page when you name it as `routes.contacts`.
Send `context.country` from your server's edge geolocation with every message too;
[Tokenized stocks](/concepts#tokenized-stocks) explains the country and purchase restrictions.

## Next steps

- [**Components reference**](/react-components) — Every block, its props and its parts.
- [**Theming**](/react-theming) — Make the blocks look like your product.
- [**View models**](/react-model) — The logic behind the blocks, for your own markup.
