Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
269c675
feat: add_page(stylesheets=...) for stylesheets only one page loads
benedikt-bartscher Nov 25, 2026
f2c7596
Merge remote-tracking branch 'github/main' into page-stylesheets
benedikt-bartscher Nov 25, 2026
8771b81
docs: link the page stylesheet example from the assets root so the do…
benedikt-bartscher Nov 25, 2026
1c67e57
docs: link the page stylesheet example from the assets root so the do…
benedikt-bartscher Nov 25, 2026
f626c69
Merge commit '1c67e57c82' into page-stylesheets
benedikt-bartscher Nov 25, 2026
0416e78
fix: keep a page's stylesheets when its @rx.page function is added again
benedikt-bartscher Nov 26, 2026
0a7f236
fix: compile a sass stylesheet named like another one to its own file
benedikt-bartscher Nov 26, 2026
2ed603b
test: navigate client-side between the pages of the page stylesheet test
benedikt-bartscher Nov 26, 2026
15e0b5a
test: compare the plain page's compiled output in full
benedikt-bartscher Nov 26, 2026
bbf8c69
fix: keep a page's stylesheets when its @rx.page function is added again
benedikt-bartscher Nov 26, 2026
d3ffa21
fix: compile a sass stylesheet named like another one to its own file
benedikt-bartscher Nov 26, 2026
d1179ac
test: navigate client-side between the pages of the page stylesheet test
benedikt-bartscher Nov 26, 2026
945a824
test: compare the plain page's compiled output in full
benedikt-bartscher Nov 26, 2026
c2e2357
Merge commit '945a824083' into page-stylesheets
benedikt-bartscher Nov 26, 2026
2377cbc
Merge branch 'main' into page-stylesheets
benedikt-bartscher Nov 26, 2026
d72b9ba
fix: take a single page stylesheet given as a string as one stylesheet
benedikt-bartscher Nov 26, 2026
29267f9
fix: give page hooks a page's stylesheets in backend-only compiles too
benedikt-bartscher Nov 26, 2026
c2d35c5
fix: load page stylesheets in an embedded app, which renders no <Links/>
benedikt-bartscher Nov 26, 2026
24d84bc
docs: say what plugins see of page stylesheets in the reflex-base news
benedikt-bartscher Nov 26, 2026
59c3190
Merge commit '24d84bcd1a' into page-stylesheets
benedikt-bartscher Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/styling/custom-stylesheets.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,20 @@ Without a leading slash the path is considered relative to the current page rout
not work for routes containing more than one path component, like `/blog/my-cool-post`.
```

## Page Stylesheets

A stylesheet that only one page needs can be passed to `add_page` (or `@rx.page`) instead. It takes the same files and URLs as `rx.App`:

```python
app.add_page(
pricing,
route="/pricing",
stylesheets=["/pricing.css"], # This path is relative to assets/
)
```

The page links its stylesheets in the `<head>` after the app's, so its rules win over the app's rules of equal specificity. On client-side navigation the stylesheets load before the page renders, and they are removed when the user leaves the page.

## Styling with CSS

You can use CSS variables directly in your Reflex app by passing them alongside the appropriae props. Create a `style.css` file inside the `assets` folder with the following lines:
Expand Down
1 change: 1 addition & 0 deletions news/+page-stylesheets.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`add_page` and `@rx.page` take `stylesheets=`, stylesheets only that page loads, after the app's: `app.add_page(pricing, stylesheets=["/pages/pricing.css"])`. They take the same asset files and URLs as `rx.App(stylesheets=...)` and become the page's React Router `links`, so they are in the prerendered `<head>`, load before the page renders on client-side navigation and are removed when it is left, in an `EmbedPlugin` widget too.
1 change: 1 addition & 0 deletions news/+stylesheet-namesakes.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A sass stylesheet named like another stylesheet next to it, such as `theme.scss` beside `theme.css`, no longer compiles to the same file in `.web/styles`, where whichever compiled last replaced the other: it keeps its suffix there, as `theme.scss.css`.
1 change: 1 addition & 0 deletions packages/reflex-base/news/+page-stylesheets.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Plugins see a page's stylesheets: the `add_page` that `register_route` receives takes `stylesheets=`, and `PageContext.stylesheets` holds them. `page_template` takes `links`, which the route module exports as React Router's `links`, and an embedded app's entry renders them with their page, as it has no `<Links/>`.
8 changes: 6 additions & 2 deletions packages/reflex-base/src/reflex_base/compiler/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from reflex_base import constants
from reflex_base.utils import memo_paths
from reflex_base.utils.format import json_dumps
from reflex_base.vars.base import VarData
from reflex_base.vars.base import Var, VarData

if TYPE_CHECKING:
from reflex.compiler.utils import _ImportDict
Expand Down Expand Up @@ -653,6 +653,7 @@ def page_template(
render: dict[str, Any],
route: str = "",
client_state_owns: Sequence[str] = (),
links: Var | None = None,
):
"""Template for a single react page.

Expand Down Expand Up @@ -684,6 +685,8 @@ def page_template(
given, the exported component is ``Component`` wrapped in a client
state scope claiming them, so hooks in the page body resolve inside
it.
links: The link descriptors the route module exports as ``links``,
which React Router renders in the head while the route is shown.

Returns:
Rendered React page component as string.
Expand All @@ -703,6 +706,7 @@ def page_template(
if client_state_owns
else "Component"
)
links_str = f"export const links = () => {links!s};\n" if links is not None else ""
return f"""{imports_str}

{dynamic_imports_str}
Expand All @@ -716,7 +720,7 @@ def page_template(
{_RenderUtils.render(render)}
)
}}
{display_name_str}
{display_name_str}{links_str}
export default {export_str};
"""

Expand Down
2 changes: 2 additions & 0 deletions packages/reflex-base/src/reflex_base/plugins/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ def __call__(
on_load: "EventType[()] | None" = None,
meta: Sequence["Mapping[str, Any] | Component"] = ...,
context: dict[str, Any] | None = None,
stylesheets: Sequence[str] = ...,
**extra_page_args: Any,
) -> None:
"""Stage a page contribution owned by the calling plugin.
Expand All @@ -93,6 +94,7 @@ def __call__(
on_load: The event handler(s) called each time the page loads.
meta: The metadata of the page.
context: Values passed to the page for custom page-specific logic.
stylesheets: Stylesheets only this page loads, after the app's.
extra_page_args: Keyword arguments added by concrete ``App``
subclasses that extend page registration.
"""
Expand Down
2 changes: 2 additions & 0 deletions packages/reflex-base/src/reflex_base/plugins/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,8 @@ class PageContext(BaseContext):
output_path: str | None = None
output_code: str | None = None
source_module: str | None = None
# The stylesheets only this page loads, as ``App.stylesheets`` takes them.
stylesheets: Sequence[str] = ()
# Stack of ``id(component)`` for components whose subtree is
# memoize-suppressed. Populated by ``MemoizeStatefulPlugin`` when it
# encounters a ``MemoizationLeaf``-style snapshot boundary and popped on
Expand Down
38 changes: 36 additions & 2 deletions packages/reflex-frontend/src/app/entry.client.embed.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,42 @@
import { startTransition, createElement } from "react";
import { startTransition, createElement, Fragment } from "react";
import { createRoot, hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";
import env from "$/env.json";

const selector = env.MOUNT_TARGET;

// Resolves once the browser has the stylesheet, as React Router waits for a
// route's stylesheets before showing it.
const preloadStylesheet = (href) =>
new Promise((resolve) => {
const link = document.createElement("link");
link.rel = "preload";
link.as = "style";
link.href = href;
link.onload = link.onerror = () => {
link.remove();
resolve();
};
document.head.append(link);
});

// Without <Links/>, a page renders the stylesheets its route module exports as
// `links` itself, so they apply while it is shown and go when it is left.
const pageComponent = async (page) => {
const links = page.links?.() ?? [];
if (!links.length) return page.default;
await Promise.all(links.map(({ href }) => preloadStylesheet(href)));
return () =>
createElement(
Fragment,
null,
...links.map((link) =>
createElement("link", { key: link.href, ...link }),
),
createElement(page.default),
);
};

if (selector) {
const target = document.querySelector(selector);
if (!target) {
Expand Down Expand Up @@ -34,7 +66,9 @@ if (selector) {
.then(([, reactRouter, root, manifest]) => {
const { createMemoryRouter, RouterProvider, Outlet } = reactRouter;
const children = manifest.default.map(({ path, load }) => {
const lazy = async () => ({ Component: (await load()).default });
const lazy = async () => ({
Component: await pageComponent(await load()),
});
if (path === "") return { index: true, lazy };
return { path, lazy };
});
Expand Down
13 changes: 13 additions & 0 deletions reflex/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,7 @@ class UnevaluatedPage:
on_load: EventType[()] | None = None
meta: Sequence[Mapping[str, Any] | Component] = ()
context: Mapping[str, Any] = dataclasses.field(default_factory=dict)
stylesheets: Sequence[str] = ()
Comment thread
benedikt-bartscher marked this conversation as resolved.
Resolved
_source_module: str | None = None

def merged_with(self, other: UnevaluatedPage) -> UnevaluatedPage:
Expand All @@ -351,6 +352,7 @@ def merged_with(self, other: UnevaluatedPage) -> UnevaluatedPage:
else other.description,
on_load=self.on_load if self.on_load is not None else other.on_load,
context=self.context if self.context is not None else other.context,
stylesheets=self.stylesheets or other.stylesheets,
_source_module=self._source_module
if self._source_module is not None
else other._source_module,
Expand Down Expand Up @@ -1581,6 +1583,7 @@ def add_page(
on_load: EventType[()] | None = None,
meta: Sequence[Mapping[str, Any] | Component] = constants.DefaultPage.META_LIST,
context: dict[str, Any] | None = None,
stylesheets: Sequence[str] = (),
):
"""Add a page to the app.

Expand All @@ -1596,6 +1599,9 @@ def add_page(
on_load: The event handler(s) that will be called each time the page load.
meta: The metadata of the page.
context: Values passed to page for custom page-specific logic.
stylesheets: Stylesheets only this page loads, after the app's, as
``App.stylesheets`` takes them: files or directories in the
assets directory, or URLs.

Raises:
BackendVarFormatError: When title, description, image or on_load is a field with no frontend var.
Expand All @@ -1613,6 +1619,7 @@ def add_page(
on_load,
meta,
context,
stylesheets=stylesheets,
)
)

Expand All @@ -1626,6 +1633,7 @@ def _prepare_page(
on_load: EventType[()] | None = None,
meta: Sequence[Mapping[str, Any] | Component] = constants.DefaultPage.META_LIST,
context: dict[str, Any] | None = None,
stylesheets: Sequence[str] = (),
) -> _PreparedPage:
"""Validate and normalize a page without mutating app route state.

Expand All @@ -1642,6 +1650,7 @@ def _prepare_page(
on_load: The event handler(s) called each time the page loads.
meta: The metadata of the page.
context: Values passed to page for custom page-specific logic.
stylesheets: Stylesheets only this page loads, after the app's.

Returns:
The validated page descriptor and its dynamic route arguments.
Expand Down Expand Up @@ -1698,6 +1707,10 @@ def _prepare_page(
on_load=on_load,
meta=meta,
context=context or {},
# A string is a sequence of strings too, one per character.
stylesheets=(stylesheets,)
if isinstance(stylesheets, str)
else tuple(stylesheets),
_source_module=source_module,
)

Expand Down
Loading
Loading