SDK React
⚛️ Componentes prontos: Hooks, Inbox embeddable e notificações real-time via WebSocket
O SDK React permite integrar notificações in-app na sua aplicação com componentes prontos e hooks. Este guia cobre:
- Instalação e setup
- Provider e configuração
- Hook
useNotifica() - Componente
<NotificaInbox /> - Notificações real-time via WebSocket
- Customização visual (CSS vars)
Instalação
npm install @notifica/react
Ou com yarn/pnpm:
yarn add @notifica/react
# ou
pnpm add @notifica/react
Requisitos: React 18+ · TypeScript 5+ (opcional, tipos incluídos)
Setup básico
Envolva sua aplicação com o <NotificaProvider>:
import { NotificaProvider } from '@notifica/react';
function App() {
return (
<NotificaProvider
publishableKey="pk_live_sua_chave"
subscriberId="user-123"
>
<YourApp />
</NotificaProvider>
);
}
Use a publishable key (começa com pk_live_ ou pk_test_), não a secret key. A publishable key é segura para uso no frontend.
Configuração avançada
<NotificaProvider
publishableKey="pk_live_..."
subscriberId="user-123"
// URL customizada (self-hosted ou staging)
baseUrl="https://api.staging.notifica.com.br"
// Intervalo de polling em ms (padrão: WebSocket)
pollingInterval={30000}
// Desabilitar WebSocket (usar polling)
disableWebSocket={false}
>
<YourApp />
</NotificaProvider>
| Prop | Padrão | Descrição |
|---|---|---|
publishableKey | Obrigatório | Sua publishable key (pk_live_...) |
subscriberId | Obrigatório | ID do subscriber logado |
baseUrl | https://api.notifica.com.br | URL base da API |
pollingInterval | — | Intervalo de polling em ms (fallback se WebSocket falhar) |
disableWebSocket | false | Forçar polling ao invés de WebSocket |
Hook useNotifica()
O hook principal para acessar notificações e ações:
import { useNotifica } from '@notifica/react';
function NotificationBell() {
const {
unreadCount,
notifications,
isLoading,
markAsRead,
markAllAsRead,
refresh,
} = useNotifica();
return (
<div>
<button onClick={refresh}>
🔔 {unreadCount > 0 && <span className="badge">{unreadCount}</span>}
</button>
{notifications.map((n) => (
<div key={n.id} onClick={() => markAsRead(n.id)}>
<strong>{n.title}</strong>
<p>{n.body}</p>
{!n.readAt && <span className="dot" />}
</div>
))}
{unreadCount > 0 && (
<button onClick={markAllAsRead}>Marcar todas como lidas</button>
)}
</div>
);
}
Retorno do hook
| Campo | Tipo | Descrição |
|---|---|---|
notifications | InAppNotification[] | Lista de notificações |
unreadCount | number | Contagem de não-lidas |
isLoading | boolean | Carregando dados |
isConnected | boolean | WebSocket conectado |
markAsRead | (id: string) => Promise<void> | Marca como lida |
markAllAsRead | () => Promise<void> | Marca todas como lidas |
refresh | () => Promise<void> | Recarrega notificações |
Tipo InAppNotification
interface InAppNotification {
id: string;
title: string;
body: string;
data?: Record<string, any>;
readAt: string | null;
createdAt: string;
}
Componente <NotificaInbox />
Inbox pronto para uso, com UI completa:
import { NotificaInbox } from '@notifica/react';
function Header() {
return (
<nav>
<h1>Meu App</h1>
<NotificaInbox />
</nav>
);
}
Props
<NotificaInbox
// Posição do popover
position="bottom-right"
// Número de notificações a carregar
limit={20}
// Texto quando não há notificações
emptyText="Nenhuma notificação"
// Título do inbox
title="Notificações"
// Callback ao clicar em notificação
onNotificationClick={(notification) => {
router.push(notification.data?.url);
}}
// Callback quando contagem muda
onUnreadCountChange={(count) => {
document.title = count > 0 ? `(${count}) Meu App` : 'Meu App';
}}
// Classes CSS customizadas
className="my-inbox"
/>
| Prop | Tipo | Padrão | Descrição |
|---|---|---|---|
position | string | "bottom-right" | Posição do popover |
limit | number | 20 | Notificações por página |
emptyText | string | "Sem notificações" | Texto vazio |
title | string | "Notificações" | Título do inbox |
onNotificationClick | function | — | Callback de clique |
onUnreadCountChange | function | — | Callback de contagem |
className | string | — | Classe CSS adicional |
Notificações real-time
O SDK usa WebSocket por padrão para receber notificações em tempo real:
import { useNotifica } from '@notifica/react';
function App() {
const { notifications, isConnected } = useNotifica();
// Novas notificações aparecem automaticamente
// sem necessidade de polling ou refresh manual
return (
<div>
<span>{isConnected ? '🟢 Conectado' : '🔴 Desconectado'}</span>
<ul>
{notifications.map((n) => (
<li key={n.id}>{n.title}</li>
))}
</ul>
</div>
);
}
Se o WebSocket falhar (firewall, proxy), o SDK faz fallback automático para polling com o intervalo configurado em pollingInterval.
Customização visual (CSS Variables)
O <NotificaInbox /> é completamente customizável via CSS variables:
:root {
/* Cores */
--notifica-primary: #22c55e;
--notifica-bg: #ffffff;
--notifica-bg-hover: #f3f4f6;
--notifica-text: #111827;
--notifica-text-secondary: #6b7280;
--notifica-border: #e5e7eb;
--notifica-unread-dot: #22c55e;
/* Layout */
--notifica-width: 380px;
--notifica-max-height: 480px;
--notifica-border-radius: 12px;
--notifica-font-family: inherit;
--notifica-font-size: 14px;
/* Sombras */
--notifica-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
}
Tema escuro
[data-theme="dark"] {
--notifica-bg: #1f2937;
--notifica-bg-hover: #374151;
--notifica-text: #f9fafb;
--notifica-text-secondary: #9ca3af;
--notifica-border: #374151;
}
Exemplo: tema customizado
.my-inbox {
--notifica-primary: #6366f1;
--notifica-border-radius: 8px;
--notifica-font-family: 'Inter', sans-serif;
--notifica-width: 420px;
}
Componente headless (sem UI)
Para controle total da UI, use apenas o hook:
import { useNotifica } from '@notifica/react';
function CustomInbox() {
const { notifications, unreadCount, markAsRead, markAllAsRead, isLoading } = useNotifica();
if (isLoading) return <Skeleton />;
return (
<div className="custom-inbox">
<div className="header">
<h3>Notificações ({unreadCount})</h3>
{unreadCount > 0 && (
<button onClick={markAllAsRead}>Limpar</button>
)}
</div>
{notifications.length === 0 ? (
<p className="empty">Tudo em dia! ✨</p>
) : (
<ul>
{notifications.map((n) => (
<li
key={n.id}
className={n.readAt ? 'read' : 'unread'}
onClick={() => markAsRead(n.id)}
>
<h4>{n.title}</h4>
<p>{n.body}</p>
<time>{new Date(n.createdAt).toLocaleString('pt-BR')}</time>
</li>
))}
</ul>
)}
</div>
);
}
Integração com Next.js
App Router (Server Components)
O provider deve ficar em um Client Component:
// app/providers.tsx
'use client';
import { NotificaProvider } from '@notifica/react';
export function Providers({ children, subscriberId }: { children: React.ReactNode; subscriberId: string }) {
return (
<NotificaProvider
publishableKey={process.env.NEXT_PUBLIC_NOTIFICA_KEY!}
subscriberId={subscriberId}
>
{children}
</NotificaProvider>
);
}
// app/layout.tsx
import { Providers } from './providers';
export default function RootLayout({ children }) {
return (
<html>
<body>
<Providers subscriberId={getCurrentUserId()}>
{children}
</Providers>
</body>
</html>
);
}
Pages Router
// _app.tsx
import { NotificaProvider } from '@notifica/react';
export default function MyApp({ Component, pageProps }) {
return (
<NotificaProvider
publishableKey={process.env.NEXT_PUBLIC_NOTIFICA_KEY!}
subscriberId={pageProps.subscriberId}
>
<Component {...pageProps} />
</NotificaProvider>
);
}
Segurança
O SDK React usa publishable keys que são seguras para o frontend:
pk_live_...— Produção (somente leitura: listar notificações, marcar como lida)pk_test_...— Sandbox
As publishable keys não podem enviar notificações, criar templates ou acessar dados de outros subscribers.
Nunca use secret keys (nk_live_...) no frontend. Elas dão acesso total à API.
FAQ
Q: Preciso usar TypeScript? A: Não. Funciona com JavaScript, mas TypeScript dá autocomplete completo.
Q: Funciona com React Native?
A: O hook useNotifica() funciona. O componente <NotificaInbox /> é web-only. Para React Native, use o hook e construa sua própria UI.
Q: O WebSocket reconecta automaticamente? A: Sim, com backoff exponencial. Se falhar 3 vezes, faz fallback para polling.
Q: Posso usar sem o Provider?
A: Não. O <NotificaProvider> gerencia conexão, cache e estado. Todos os hooks e componentes precisam dele.
Q: Como testo em desenvolvimento?
A: Use pk_test_... e envie notificações in-app via API ou dashboard. Elas aparecem no Inbox em real-time.
Links
- npm: npmjs.com/package/@notifica/react
- GitHub: github.com/notifica-tech/notifica-react
- In-App Inbox: In-App Inbox
- API Reference: API Reference