Embed Web Libraries in Native Mobile Apps with DOM Components
Runs web-only React libraries and code verbatim in an Expo app via DOM components, rendered natively as a webview.
Why it matters
Enable developers to use any React web library (charts, syntax highlighters, rich text editors) directly in Expo native mobile apps by rendering them in isolated webviews while maintaining native performance for the rest of the app.
Outcomes
What it gets done
Render web-only libraries like recharts and react-syntax-highlighter in native iOS/Android apps without modification
Bridge native functionality to webview components through async function props for alerts, storage, and native APIs
Configure webview behavior with scroll control, safe area handling, and custom sizing through the dom prop
Migrate existing React web components to mobile by adding the 'use dom' directive and following serializable props rules
Install
Add it to your toolbox
Run in your project directory:
curl -fsSL https://spark.entire.vc/get/ag-use-dom | bash Overview
Use Dom
This skill covers Expo's DOM Components feature - running web-only React libraries and code verbatim inside a native webview via the 'use dom' directive, including the dom prop, native-action exposure, CSS handling, and expo-router integration. Use DOM components for web-only libraries, complex CSS, or migrating web code without a rewrite - avoid them for simple UI, performance-critical surfaces, deep native integration, or layout route files.
What it does
Covers Expo's DOM Components feature: web code that runs verbatim in a webview on native platforms while rendering as-is on web, letting web-only React libraries (recharts, react-syntax-highlighter, and similar) run inside an Expo app unmodified.
Use DOM components for web-only libraries dependent on DOM APIs (charts, syntax highlighters, rich text editors), migrating existing React web components without a rewrite, complex HTML/CSS layouts unavailable in React Native, iframes/embeds needing a browser context, or Canvas/WebGL. Avoid them where native performance is critical (webviews add overhead), for simple UI (native components are more efficient), for deep native-API integration (use local modules instead), or for _layout route files, which cannot be DOM components.
// components/WebChart.tsx
"use dom";
export default function WebChart({
data,
}: {
data: number[];
dom: import("expo/dom").DOMProps;
}) {
return (
<div style={{ padding: 20 }}>
<h2>Chart Data</h2>
<ul>
{data.map((value, i) => (
<li key={i}>{value}</li>
))}
</ul>
</div>
);
}
Every DOM component file must start with a 'use dom'; directive, export exactly one React component as default, live in its own file (never inline or combined with native components), accept only serializable props (strings, numbers, booleans, arrays, plain objects), and import its own CSS - DOM components run in an isolated JS context. Every DOM component also receives a special dom prop (typed via import("expo/dom").DOMProps) for webview configuration - options include scrollEnabled, contentInsetAdjustmentBehavior: "never" (to flow under the notch), and a style object for manual sizing.
Native functionality is exposed to the webview by passing async functions as props from the native parent (e.g. showAlert, saveData callbacks a DOM component can call and await). CSS can be imported directly in the component file or written as inline styles/CSS-in-JS. The expo-router <Link /> component and useRouter() work directly inside DOM components, but several router hooks needing synchronous native routing state - useLocalSearchParams, useGlobalSearchParams, usePathname, useSegments, useRootNavigation, useRootNavigationState - don't work directly and must instead be read in the native parent and passed down as props. An IS_DOM export from expo/dom detects whether code is currently running inside a DOM component. Assets should be require()d and bundled with the component rather than served from the public directory.
Platform behavior differs: iOS renders in WKWebView, Android in WebView, and web renders as-is with no webview wrapper (the dom prop is simply ignored there).
When to use - and when NOT to
Use DOM components to bring web-only React libraries or complex HTML/CSS into an Expo app without a native rewrite. Avoid them for simple UI, performance-critical surfaces, deep native API access, or layout route files. Keep them focused - don't put entire screens inside a webview - and remember the webview has its own JS context with no direct state sharing with native code.
Inputs and outputs
Input is a React web component (or web library usage) that needs to run inside an Expo app. Output is a 'use dom'-directived component file that native screens import and render like any other component, configured via the dom prop.
Integrations
Works with any web-only React library (recharts, react-syntax-highlighter, etc.), expo-router's <Link />/useRouter(), and native functionality exposed via async function props from the native parent.
Who it's for
Expo/React Native developers who need a web-only library or existing React web component running inside their app without a native rewrite, and want the DOM-component rules, prop patterns, and router workarounds without re-deriving them from Expo's documentation.
Source README
What are DOM Components?
DOM components allow web code to run verbatim in a webview on native platforms while rendering as-is on web. This enables using web-only libraries like recharts, react-syntax-highlighter, or any React web library in your Expo app without modification.
When to Use DOM Components
Use DOM components when you need:
- Web-only libraries - Charts (recharts, chart.js), syntax highlighters, rich text editors, or any library that depends on DOM APIs
- Migrating web code - Bring existing React web components to native without rewriting
- Complex HTML/CSS layouts - When CSS features aren't available in React Native
- iframes or embeds - Embedding external content that requires a browser context
- Canvas or WebGL - Web graphics APIs not available natively
When NOT to Use DOM Components
Avoid DOM components when:
- Native performance is critical - Webviews add overhead
- Simple UI - React Native components are more efficient for basic layouts
- Deep native integration - Use local modules instead for native APIs
- Layout routes -
_layoutfiles cannot be DOM components
Basic DOM Component
Create a new file with the 'use dom'; directive at the top:
// components/WebChart.tsx
"use dom";
export default function WebChart({
data,
}: {
data: number[];
dom: import("expo/dom").DOMProps;
}) {
return (
<div style={{ padding: 20 }}>
<h2>Chart Data</h2>
<ul>
{data.map((value, i) => (
<li key={i}>{value}</li>
))}
</ul>
</div>
);
}
Rules for DOM Components
- Must have
'use dom';directive at the top of the file - Single default export - One React component per file
- Own file - Cannot be defined inline or combined with native components
- Serializable props only - Strings, numbers, booleans, arrays, plain objects
- Include CSS in the component file - DOM components run in isolated context
The dom Prop
Every DOM component receives a special dom prop for webview configuration. Always type it in your props:
"use dom";
interface Props {
content: string;
dom: import("expo/dom").DOMProps;
}
export default function MyComponent({ content }: Props) {
return <div>{content}</div>;
}
Common dom Prop Options
// Disable body scrolling
<DOMComponent dom={{ scrollEnabled: false }} />
// Flow under the notch (disable safe area insets)
<DOMComponent dom={{ contentInsetAdjustmentBehavior: "never" }} />
// Control size manually
<DOMComponent dom={{ style: { width: 300, height: 400 } }} />
// Combine options
<DOMComponent
dom={{
scrollEnabled: false,
contentInsetAdjustmentBehavior: "never",
style: { width: '100%', height: 500 }
}}
/>
Exposing Native Actions to the Webview
Pass async functions as props to expose native functionality to the DOM component:
// app/index.tsx (native)
import { Alert } from "react-native";
import DOMComponent from "@/components/dom-component";
export default function Screen() {
return (
<DOMComponent
showAlert={async (message: string) => {
Alert.alert("From Web", message);
}}
saveData={async (data: { name: string; value: number }) => {
// Save to native storage, database, etc.
console.log("Saving:", data);
return { success: true };
}}
/>
);
}
// components/dom-component.tsx
"use dom";
interface Props {
showAlert: (message: string) => Promise<void>;
saveData: (data: {
name: string;
value: number;
}) => Promise<{ success: boolean }>;
dom?: import("expo/dom").DOMProps;
}
export default function DOMComponent({ showAlert, saveData }: Props) {
const handleClick = async () => {
await showAlert("Hello from the webview!");
const result = await saveData({ name: "test", value: 42 });
console.log("Save result:", result);
};
return <button onClick={handleClick}>Trigger Native Action</button>;
}
Using Web Libraries
DOM components can use any web library:
// components/syntax-highlight.tsx
"use dom";
import SyntaxHighlighter from "react-syntax-highlighter";
import { docco } from "react-syntax-highlighter/dist/esm/styles/hljs";
interface Props {
code: string;
language: string;
dom?: import("expo/dom").DOMProps;
}
export default function SyntaxHighlight({ code, language }: Props) {
return (
<SyntaxHighlighter language={language} style={docco}>
{code}
</SyntaxHighlighter>
);
}
// components/chart.tsx
"use dom";
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
} from "recharts";
interface Props {
data: Array<{ name: string; value: number }>;
dom: import("expo/dom").DOMProps;
}
export default function Chart({ data }: Props) {
return (
<LineChart width={400} height={300} data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Line type="monotone" dataKey="value" stroke="#8884d8" />
</LineChart>
);
}
CSS in DOM Components
CSS imports must be in the DOM component file since they run in isolated context:
// components/styled-component.tsx
"use dom";
import "@/styles.css"; // CSS file in same directory
export default function StyledComponent({
dom,
}: {
dom: import("expo/dom").DOMProps;
}) {
return (
<div className="container">
<h1 className="title">Styled Content</h1>
</div>
);
}
Or use inline styles / CSS-in-JS:
"use dom";
const styles = {
container: {
padding: 20,
backgroundColor: "#f0f0f0",
},
title: {
fontSize: 24,
color: "#333",
},
};
export default function StyledComponent({
dom,
}: {
dom: import("expo/dom").DOMProps;
}) {
return (
<div style={styles.container}>
<h1 style={styles.title}>Styled Content</h1>
</div>
);
}
Expo Router in DOM Components
The expo-router <Link /> component and router API work inside DOM components:
"use dom";
import { Link, useRouter } from "expo-router";
export default function Navigation({
dom,
}: {
dom: import("expo/dom").DOMProps;
}) {
const router = useRouter();
return (
<nav>
<Link href="/about">About</Link>
<button onClick={() => router.push("/settings")}>Settings</button>
</nav>
);
}
Router APIs That Require Props
These hooks don't work directly in DOM components because they need synchronous access to native routing state:
useLocalSearchParams()useGlobalSearchParams()usePathname()useSegments()useRootNavigation()useRootNavigationState()
Solution: Read these values in the native parent and pass as props:
// app/[id].tsx (native)
import { useLocalSearchParams, usePathname } from "expo-router";
import DOMComponent from "@/components/dom-component";
export default function Screen() {
const { id } = useLocalSearchParams();
const pathname = usePathname();
return <DOMComponent id={id as string} pathname={pathname} />;
}
// components/dom-component.tsx
"use dom";
interface Props {
id: string;
pathname: string;
dom?: import("expo/dom").DOMProps;
}
export default function DOMComponent({ id, pathname }: Props) {
return (
<div>
<p>Current ID: {id}</p>
<p>Current Path: {pathname}</p>
</div>
);
}
Detecting DOM Environment
Check if code is running in a DOM component:
"use dom";
import { IS_DOM } from "expo/dom";
export default function Component({
dom,
}: {
dom?: import("expo/dom").DOMProps;
}) {
return <div>{IS_DOM ? "Running in DOM component" : "Running natively"}</div>;
}
Assets
Prefer requiring assets instead of using the public directory:
"use dom";
// Good - bundled with the component
const logo = require("../assets/logo.png");
export default function Component({
dom,
}: {
dom: import("expo/dom").DOMProps;
}) {
return <img src={logo} alt="Logo" />;
}
Usage from Native Components
Import and use DOM components like regular components:
// app/index.tsx
import { View, Text } from "react-native";
import WebChart from "@/components/web-chart";
import CodeBlock from "@/components/code-block";
export default function HomeScreen() {
return (
<View style={{ flex: 1 }}>
<Text>Native content above</Text>
<WebChart data={[10, 20, 30, 40, 50]} dom={{ style: { height: 300 } }} />
<CodeBlock
code="const x = 1;"
language="javascript"
dom={{ scrollEnabled: true }}
/>
<Text>Native content below</Text>
</View>
);
}
Platform Behavior
| Platform | Behavior |
|---|---|
| iOS | Rendered in WKWebView |
| Android | Rendered in WebView |
| Web | Rendered as-is (no webview wrapper) |
On web, the dom prop is ignored since no webview is needed.
Tips
- DOM components hot reload during development
- Keep DOM components focused - don't put entire screens in webviews
- Use native components for navigation chrome, DOM components for specialized content
- Test on all platforms - web rendering may differ slightly from native webviews
- Large DOM components may impact performance - profile if needed
- The webview has its own JavaScript context - cannot directly share state with native
Limitations
- Use this skill only when the task clearly matches its upstream product or API scope.
- Verify commands, API behavior, pricing, quotas, credentials, and deployment effects against current official documentation before making changes.
- Do not treat generated examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.
FAQ
Common questions
Discussion
Questions & comments · 0
Sign In Sign in to leave a comment.