Loading...
Loading...
Guide for building full-stack web applications using Reflex, a Python framework that compiles to React frontend and FastAPI backend. Use when creating, modifying, or debugging Reflex apps - covers state management, event handlers, components, routing, styling, and data integration patterns.
npx skill4agent add silvainfm/claude-skills reflex-devimport reflex as rx
class AppState(rx.State):
# State variables (any JSON-serializable type)
count: int = 0
items: list[str] = []
user_name: str = ""
# Event handlers - the ONLY way to modify state
def increment(self):
self.count += 1
def add_item(self, item: str):
self.items.append(item)
# Computed vars (derived state)
@rx.var
def item_count(self) -> int:
return len(self.items)@rx.varimport reflex as rx
def header() -> rx.Component:
return rx.heading("My App", size="lg")
def counter_component(state: AppState) -> rx.Component:
return rx.vstack(
rx.text(f"Count: {state.count}"),
rx.button("Increment", on_click=state.increment),
spacing="4"
)rx.vstackrx.hstackrx.boxrx.containerrx.headingrx.textrx.coderx.inputrx.text_arearx.selectrx.checkboxrx.buttonrx.linkrx.icon_buttonrx.tablerx.data_tablerx.listrx.recharts.line_chartrx.recharts.bar_chartclass FormState(rx.State):
form_data: dict[str, str] = {}
# Simple event handler
def handle_submit(self):
print(f"Submitted: {self.form_data}")
# Event handler with argument
def update_field(self, field: str, value: str):
self.form_data[field] = value
# Async event handler (for API calls, DB queries)
async def fetch_data(self):
# Can use any Python library
import httpx
async with httpx.AsyncClient() as client:
response = await client.get("https://api.example.com/data")
self.data = response.json()on_clickon_changeon_submiton_mounton_bluron_focusmy_app/
├── my_app/
│ ├── __init__.py # Empty
│ └── my_app.py # Main app file (State + pages)
├── assets/ # Static files (images, fonts, etc.)
├── .web/ # Auto-generated frontend (don't edit)
├── rxconfig.py # Reflex configuration
└── requirements.txt # Python dependenciesimport reflex as rx
# 1. Define State
class State(rx.State):
count: int = 0
def increment(self):
self.count += 1
# 2. Define Pages
def index() -> rx.Component:
return rx.container(
rx.heading("Welcome"),
rx.button("Click", on_click=State.increment),
rx.text(f"Count: {State.count}")
)
def about() -> rx.Component:
return rx.container(
rx.heading("About"),
rx.link("Home", href="/")
)
# 3. Create App and Add Routes
app = rx.App()
app.add_page(index, route="/")
app.add_page(about, route="/about")class FormState(rx.State):
name: str = ""
email: str = ""
def handle_submit(self, form_data: dict):
self.name = form_data.get("name", "")
self.email = form_data.get("email", "")
def form_page():
return rx.form(
rx.vstack(
rx.input(name="name", placeholder="Name"),
rx.input(name="email", placeholder="Email"),
rx.button("Submit", type="submit"),
),
on_submit=FormState.handle_submit,
)class DataState(rx.State):
data: list[dict] = [
{"id": 1, "name": "Alice", "age": 25},
{"id": 2, "name": "Bob", "age": 30},
]
def data_table_page():
return rx.data_table(
data=DataState.data,
columns=["id", "name", "age"],
sort=True,
search=True,
pagination=True,
)class UploadState(rx.State):
async def handle_upload(self, files: list[rx.UploadFile]):
for file in files:
upload_data = await file.read()
# Process file data
outfile = f"./uploads/{file.filename}"
with open(outfile, "wb") as f:
f.write(upload_data)
def upload_page():
return rx.vstack(
rx.upload(
rx.button("Select Files"),
id="upload1",
),
rx.button(
"Upload",
on_click=UploadState.handle_upload(rx.upload_files(upload_id="upload1"))
),
)import duckdb
import polars as pl
class DBState(rx.State):
records: list[dict] = []
async def load_data(self):
# Use existing database connection
conn = duckdb.connect("data/mydb.duckdb")
df = conn.execute("SELECT * FROM mytable").pl()
self.records = df.to_dicts()
conn.close()
async def insert_record(self, data: dict):
conn = duckdb.connect("data/mydb.duckdb")
conn.execute(
"INSERT INTO mytable (name, value) VALUES (?, ?)",
[data["name"], data["value"]]
)
conn.close()
await self.load_data() # Refreshrx.box(
rx.text("Styled text"),
bg="#1a5f9e",
color="white",
padding="4",
border_radius="md",
)rx.container(
rx.responsive_grid(
rx.box("Item 1", bg="blue"),
rx.box("Item 2", bg="green"),
rx.box("Item 3", bg="red"),
columns=[1, 2, 3], # 1 col mobile, 2 tablet, 3 desktop
spacing="4",
),
max_width="1200px",
)widthheightpaddingmargindisplaybgcolorfont_sizefont_weighttext_alignborderborder_radiusborder_colorspacinggapapp = rx.App()
# Route with parameters
@rx.page(route="/user/[id]")
def user_page() -> rx.Component:
return rx.text(f"User ID: {State.router.page.params.get('id')}")
# Simple routes
app.add_page(index, route="/")
app.add_page(about, route="/about")# Links
rx.link("Go to About", href="/about")
# Programmatic navigation
def go_home(self):
return rx.redirect("/")pip install reflex
reflex initreflex runhttp://localhost:3000reflex run # Start dev server
reflex export # Build production bundle
reflex db init # Initialize database (if using Reflex DB)
reflex db migrate # Run migrationsclass AuthState(rx.State):
user: str = ""
class DataState(rx.State):
items: list = []def card(title: str, content: str) -> rx.Component:
return rx.box(
rx.heading(title, size="md"),
rx.text(content),
padding="4",
border="1px solid #ddd",
)async def fetch_data(self):
# Async I/O won't block other users
self.data = await some_api_call()count: int = 0
items: list[str] = []
def update_count(self, value: int) -> None:
self.count = valueexamples/references/patterns.md