@gravity-ai/react
v1.2.0
Published
React components for rendering Gravity AI advertisements
Readme
@gravity-ai/react
React components for rendering Gravity ads with automatic impression and click tracking.
Installation
npm install @gravity-ai/reactPeer dependency: React 17+
Quick Start
import { GravityAd } from '@gravity-ai/react';
function ChatResponse({ ads }) {
return ads.map((ad, i) => <GravityAd key={i} ad={ad} />);
}That's it. When the response contains a server-delivered renderer_spec, the component validates and renders that placement design. Otherwise it falls back to its bundled card. It automatically fires the impression pixel when the ad scrolls into view.
API Response Shape
The components expect the objects returned by the Gravity API:
interface AdResponse {
adText: string;
title?: string;
cta?: string;
brandName?: string;
url?: string;
favicon?: string;
impUrl?: string; // impression tracking pixel
clickUrl?: string; // tracked click-through URL
renderer_spec?: RendererSpec | string; // optional server-delivered placement design
}Components
<GravityAd />
Full-featured ad renderer with automatic impression/click tracking. Bundled variants use inline styles; server-delivered designs use validated inline declarations plus optional semantic CSS variables. No CSS-in-JS runtime is required.
<GravityAd
ad={ad}
// Leave `variant` unset to accept the placement's server-delivered design.
showLabel={true}
labelText="Sponsored"
openInNewTab={true}
onImpression={() => console.log('seen')}
onClickTracked={() => console.log('clicked')}
/>Variants:
| Variant | Description |
|---------|-------------|
| card | Default. Vertical card with border, shadow, and padding. |
| inline | Horizontal layout for sidebars or toolbars. |
| minimal | No border, shadow, or background. Blends with host content. |
Passing variant deliberately pins one of these bundled looks and ignores renderer_spec. Use that only when the publisher must own the layout locally.
Server-delivered placement designs
Gravity can attach a versioned renderer_spec to an ad response. When variant is unset, <GravityAd>:
- Parses and structurally validates the spec.
- Resolves its content bindings (
title,adText,cta,brandName,favicon,url). - Applies the publisher's semantic theme variables.
- Renders through a safe node whitelist (
box,text,image,link). - Falls back to the bundled
cardrenderer if the spec is malformed or resolves to no content.
The standard card spec uses one root link bound to url, so the whole visible ad routes through clickUrl; it never nests anchors. Specs must include a visible disclosure such as AD, Sponsored, Promoted, or Paid. If disclosure is missing, the SDK overlays its built-in ad badge.
Web ad requests should send specCapabilities: "web1" (and must not send supportsSpec: false). Existing integrations that send neither field remain backward-compatible and are treated as web-capable for publisher placement defaults.
Server designs adopt these optional host variables, falling back to the SDK palette:
| Variable | Purpose |
|----------|---------|
| --gravity-bg | Card/background surface |
| --gravity-text | Primary text |
| --gravity-text-muted | Secondary text |
| --gravity-accent | CTA/accent |
| --gravity-accent-foreground | Text on the accent |
| --gravity-muted | Muted surface |
| --gravity-border | Borders |
| --gravity-radius | Card radius |
When a --gravity-* variable is absent, the renderer uses the matching host variable (--card, --foreground, --primary, etc.) before its literal fallback.
Styling with style and slotProps
Override the outer container with the style prop:
<GravityAd ad={ad} style={{ maxWidth: 400, borderRadius: 16 }} />Override any inner element with slotProps:
<GravityAd
ad={ad}
slotProps={{
cta: { style: { background: '#E11D48', borderRadius: 999 } },
label: { style: { display: 'none' } },
title: { style: { fontSize: 16 } },
}}
/>Each slotProps key maps to a DOM element:
| Key | Element | What it controls |
|-----|---------|------------------|
| container | Outer <a> | Same as top-level style prop |
| inner | Padding wrapper <div> | Layout, padding, gap |
| header | Header row <div> | Favicon + brand + label row |
| favicon | Favicon <img> | Size, border-radius |
| brand | Brand name <span> | Font, color |
| label | "Sponsored" <span> | Pill styling, visibility |
| body | Body wrapper <div> | Title + text layout |
| title | Title <p> | Font, color |
| text | Ad text <p> | Font, color |
| cta | CTA button <span> | Background, border-radius, padding |
Each slot accepts { style?: CSSProperties; className?: string }.
For the full styling guide with DOM structure and common recipes, see STYLING.md.
<GravityLeadFormAd />
Lead-form ads default to a native-feeling bottom-right modal. Use
displayOverride="inline" when the form should live directly in your
layout; inline mode renders the full styled form in place (no popup) with no
internal scroll container, so the host page controls scrolling.
<GravityLeadFormAd
ad={ad}
sessionId={sessionId}
apiKey={apiKey}
userEmail={user.email}
slotProps={{
card: { className: 'my-chat-lead-card' },
submit: { style: { background: '#111827' } },
}}
/>Stable CSS hooks are included on every lead-form element, including:
gravity-lf-trigger, gravity-lf-overlay, gravity-lf-card,
gravity-lf-header, gravity-lf-title, gravity-lf-description,
gravity-lf-field, gravity-lf-input, gravity-lf-consent,
gravity-lf-submit, and gravity-lf-close. The component also exposes CSS
variables like --gravity-leadform-surface,
--gravity-leadform-border, --gravity-leadform-shadow, and
--gravity-leadform-accent.
<AdText />
Unstyled text-only renderer. Use when you want full control over presentation.
<AdText
ad={ad}
className="my-custom-style"
style={{ fontSize: 14 }}
/>Renders ad.adText as a link (if clickUrl exists) or a span. No built-in styles beyond text-decoration: none; color: inherit.
Impression Tracking
Both components use IntersectionObserver to fire the impression pixel only when the ad is actually visible to the user (50% of the element in the viewport). This is a significant improvement over fire-on-mount — publishers won't report impressions for ads rendered below the fold that were never seen.
The impression fires exactly once per ad. If the ad object changes (different impUrl), the tracking resets for the new ad.
To disable automatic tracking:
<GravityAd ad={ad} disableImpressionTracking />Hooks
useAdTracking
Low-level hook for building fully custom ad components:
import { useAdTracking } from '@gravity-ai/react';
function CustomAd({ ad }) {
const { containerRef, handleClick } = useAdTracking({
ad,
onImpression: () => console.log('impression fired'),
onClickTracked: () => console.log('click tracked'),
});
return (
<a ref={containerRef} href={ad.clickUrl} onClick={handleClick}>
{ad.adText}
</a>
);
}The hook returns:
containerRef— attach to the DOM element for IntersectionObserver-based impression trackinghandleClick— call on click to fire the click tracking callbackimpressionFired— boolean indicating whether the impression has already been fired
License
MIT
