Writing Webflow code components in React, with Tailwind
Declaring props for designers, getting Tailwind into the Shadow DOM, then bundling and sharing a small React library as Webflow code components.
With React in a Webflow Embed script tag, changing one line of copy means opening a code field. Code components fix that. You write normal React and declare which props the Designer shows, and Webflow DevLink pushes the set to the workspace as a library. My test library has a shadcn-style Button and a product grid that pulls from an API, on Next.js 16, with @webflow/react 1.2.2, @webflow/data-types 1.2.2 and @webflow/webflow-cli 1.13.1.
Each component gets its own Shadow DOM and React root
A code component is a bundled React component whose props show up in the Designer's right panel as fields, dropdowns and image pickers. Each renders in its own Shadow DOM with its own React root, server-rendered by default and then hydrated.
With separate roots, code components can't share React Context, even when nested through slots. Shared state means URL params, localStorage, custom events on window or a small store like Nano Stores.
Props are declared in a .webflow.tsx file
A *.webflow.tsx file next to the component wraps it with declareComponent and maps each prop to a Webflow data type. The component itself has no Webflow imports. webflow.json picks these files up with the glob ./components/**/*.webflow.@(js|jsx|mjs|ts|tsx).
// components/ui/Button/button.webflow.tsx
import { Button } from "./button";
import { props } from "@webflow/data-types";
import { declareComponent } from "@webflow/react";
import "../../../app/globals.css";
export default declareComponent(Button, {
name: "Button",
description: "A shadcn-style button",
group: "Interaction",
props: {
variant: props.Variant({
name: "Variant",
options: ["default", "destructive", "outline", "secondary", "ghost", "link"],
defaultValue: "default",
}),
size: props.Variant({
name: "Size",
options: ["default", "sm", "lg", "icon"],
defaultValue: "default",
}),
children: props.Text({ name: "Text", defaultValue: "Button" }),
disabled: props.Visibility({ name: "Disabled", defaultValue: false }),
},
});
props.Variant turns a cva variant into a dropdown, so the designer's pick always matches buttonVariants. Other types include Text, Number (with min, max), Boolean, Link, Image and Slot. There's no color type. The FAQ adds that a component needs exactly one root element (no fragments), and a prop name starting with __wf_ fails the bundle.
Keep the fetch out of the presentational component
ProductListing is pure and renders an array. ProductListingWidget fetches in useEffect and passes it down. The widget is what gets declared, with the API URL (default dummyjson.com/products), item count, columns, two toggles and an accent colour typed as Text as props.
"use client";
import * as React from "react";
import { ProductListing, type Product } from "./product-listing";
type Props = { apiUrl: string; limit: number; columns: number; showRating: boolean };
export function ProductListingWidget({ apiUrl, limit, ...view }: Props) {
const [products, setProducts] = React.useState<Product[] | null>(null);
const [error, setError] = React.useState<string | null>(null);
React.useEffect(() => {
fetch(`${apiUrl}?limit=${limit}`)
.then((r) => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
})
// accept both { products: [...] } and a plain array
.then((data) => setProducts(Array.isArray(data) ? data : data.products ?? []))
.catch((e: Error) => setError(e.message));
}, [apiUrl, limit]);
if (error) return <div role="alert">{error}</div>;
if (!products) return <div>Loading...</div>;
return <ProductListing products={products} {...view} />;
}
The docs say data fetching is client-side only and React Server Components aren't supported, so the server HTML is just the loading state. The pure ProductListing also works in a Next.js page in the same repo as an async Server Component with revalidate: 60 (see the SSR, SSG and ISR post).
The API has to allow CORS from the Webflow site, with no keys in the code. Components can't read .env, so configuration comes through props, and the API URL is a Text prop. A component that reads window or localStorage during render should set options: { ssr: false }.
Tailwind has to be compiled into the bundle
Shadow DOM blocks in both directions. Your CSS stays out of the page, and the site's classes and tag selectors stay out of the component (unless you set applyTagSelectors: true). The CLI's webpack runs CSS through css-loader and postcss-loader, and @tailwindcss/postcss in postcss.config.mjs is enough for Tailwind v4. For styles every component shares, the docs suggest a global decorators file that imports globals.css, referenced as library.globals in webflow.json.
A PostCSS plugin in the CLI rewrites :root to :host, so variables on :root still resolve, while a body { ... } rule doesn't match anything.
In my repo, globals.css is still the create-next-app default, with only --background and --foreground. The Button's shadcn classes (bg-primary, bg-destructive…) have no --color-* variables behind them, so Tailwind v4 doesn't generate color utilities and the variants render without fills. My fix would point the shadcn tokens at the site's variables with a fallback, so the designer's palette would apply to the component:
@import "tailwindcss";
/* use the exact names from "Copy CSS" in the Variables panel */
@theme inline {
--color-primary: var(--brand-primary, #18181b);
--color-primary-foreground: var(--brand-on-primary, #fafafa);
--color-accent: var(--brand-accent, #f4f4f5);
--color-accent-foreground: var(--brand-on-accent, #18181b);
--color-destructive: var(--brand-danger, #dc2626);
}
--font-sans points at a next/font variable Webflow doesn't have, but inherited properties cross the shadow boundary, so font-family: inherit picks up the site's font. I'm not sure @font-face inside a shadow root works in every browser, so fonts load at the site level.
The className prop I exposed is useless, since Tailwind only generates classes it saw at build time.
A webpack override and a shim
CLI 1.13.1 bundles with webpack, and the client build is a Module Federation remote. You merge an override in through library.bundleConfig, where module.rules can be a function that receives the defaults. The bundle limit is 50 MB.
// webpack.webflow.js
const path = require("path");
module.exports = {
mode: "development",
resolve: {
alias: {
"@": path.resolve(process.cwd()), // shadcn imports "@/lib/utils"
},
},
};
The @ alias may be redundant, since the CLI adds tsconfig-paths-webpack-plugin itself. mode: "development" turns off minification and I forgot it there. The --dev flag is the right tool for debugging.
The CLI pulls in @module-federation/enhanced 0.20.0, which requires webpack/lib/util/create-schema-validation, a file webpack 5.106.2 doesn't have. My fix is a postinstall script that writes a shim when it's missing:
// written to node_modules/webpack/lib/util/create-schema-validation.js
const { validate } = require("schema-utils");
const memoize = (fn) => {
let done = false;
let result;
return () => (done ? result : ((done = true), (result = fn())));
};
module.exports = (check, getSchema, options) => {
getSchema = memoize(getSchema);
return (value) => {
if (!check(value)) validate(getSchema(), value, options);
};
};
Writing into node_modules is a hack that breaks when webpack rearranges its internals, so check whether a newer CLI fixed the dependency first.
Sharing to the workspace
webflow library share stores WEBFLOW_WORKSPACE_API_TOKEN in .env after the first login (only a Workspace Admin can create it). The current docs call it webflow devlink import, with --no-input for CI, so check webflow --help on your version.
The library deploys as one unit with no versioning, and each import replaces the last. I'd tie every share to a git commit and let CI run it only from main.
I haven't tested whether Webflow Interactions reach inside a code component. CSS transitions and @keyframes do work in the shadow root, so motion stays in the component behind a Variant prop.
Pulled into a Next.js app on Webflow Cloud, builtins like Section came across but code components arrived as stubs rendering "This builtin is not currently supported: Code Island". Import those from your own code.
When I'd pick a code component
When a designer will reuse it and edit its copy, variant, images or endpoint, when it's real UI with state, or when it needs shielding from the site's CSS. Analytics, chat widgets, scripts that change elements Webflow already renders, and one-offs are still faster as embeds.
Starting over, I'd drop className, use props.Boolean for disabled, and have the grid render placeholders on the canvas, where useWebflowContext() reports mode: "design" and a live API call is wasted.
More posts
- 01
Deploying Next.js and NestJS to AWS EC2 with Docker Compose
How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.
- 02
How I store OAuth tokens for social media APIs in NestJS
OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.
- 03
llms.txt on my Next.js site, and now Lighthouse grades it
vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.