Skip to content

Navigation

A React Navigation-style API: a NavigationContainer holds one or more navigators (stack, tab, or drawer), and any descendant component can navigate through the Navigation handle from use_navigation or read its current Route with use_route.

Navigation: stack, tab, and drawer navigators with a React Navigation-style API.

import pythonnative as pn

Stack = pn.create_stack_navigator()

@pn.component
def HomeScreen():
    nav = pn.use_navigation()
    return pn.Button("Open 42", on_press=lambda: nav.navigate("Detail", id=42))

@pn.component
def DetailScreen():
    route = pn.use_route()
    return pn.Text(f"Item {route.params['id']}")

@pn.component
def App():
    return pn.NavigationContainer(
        Stack.Navigator(
            Stack.Screen("Home", HomeScreen, title="Home"),
            Stack.Screen("Detail", DetailScreen, options=lambda route: {"title": f"Item {route.params['id']}"}),
        )
    )

Public surface (all re-exported from pythonnative):

Stack, tab, and drawer navigators built on one shared core.

All three navigators are ordinary components. Each owns a NavigationState in use_state, wraps it in a NavigatorCore, and renders its screens under a Navigation provider. Only the rendering differs:

  • Stack: keeps every route mounted (hidden below the top one) so popping back restores the previous screen's state, and draws a header with a back button. When the stack is the root of a native host it pushes real native screens instead and lets the host draw the navigation bar.
  • Tabs: keeps visited tabs alive and hidden (lazy mounts them on first focus; unmount_on_blur opts out), and renders the native TabBar.
  • Drawer: like tabs, with a slide-in menu instead of a tab bar.

Inactive screens read False from use_is_focused; focus and blur listeners fire as the active route changes.

Classes:

Name Description
StackNavigator

Factory returned by create_stack_navigator.

TabNavigator

Factory returned by create_tab_navigator.

DrawerNavigator

Factory returned by create_drawer_navigator.

Functions:

Name Description
create_stack_navigator

Create a stack navigator: push and pop screens with history.

create_tab_navigator

Create a tab navigator with a native tab bar.

create_drawer_navigator

Create a drawer navigator: sibling screens behind a slide-in menu.

StackNavigator

Factory returned by create_stack_navigator.

Methods:

Name Description
Screen

Define a screen. options may be a dict or (route) -> dict; keywords merge on top.

Navigator

Render the stack with the given screens (the first, or initial_route, shows first).

Screen staticmethod

Screen(
    name: str,
    component: Callable[[], Any],
    *,
    options: Any = None,
    initial_params: Optional[Dict[str, Any]] = None,
    **option_kwargs: Unpack[ScreenOptions]
) -> ScreenDef

Define a screen. options may be a dict or (route) -> dict; keywords merge on top.

Navigator staticmethod

Navigator(
    *screens: ScreenDef,
    initial_route: Optional[str] = None,
    key: Optional[str] = None
) -> Element

Render the stack with the given screens (the first, or initial_route, shows first).

TabNavigator

Factory returned by create_tab_navigator.

Methods:

Name Description
Screen

Define a tab. options may be a dict or (route) -> dict; keywords merge on top.

Navigator

Render the tab bar with the given screens (the first, or initial_route, is selected first).

Screen staticmethod

Screen(
    name: str,
    component: Callable[[], Any],
    *,
    options: Any = None,
    initial_params: Optional[Dict[str, Any]] = None,
    **option_kwargs: Unpack[ScreenOptions]
) -> ScreenDef

Define a tab. options may be a dict or (route) -> dict; keywords merge on top.

Navigator staticmethod

Navigator(
    *screens: ScreenDef,
    initial_route: Optional[str] = None,
    key: Optional[str] = None
) -> Element

Render the tab bar with the given screens (the first, or initial_route, is selected first).

DrawerNavigator

Factory returned by create_drawer_navigator.

Methods:

Name Description
Screen

Define a drawer screen. options may be a dict or (route) -> dict; keywords merge on top.

Navigator

Render the drawer with the given screens (the first, or initial_route, shows first).

Screen staticmethod

Screen(
    name: str,
    component: Callable[[], Any],
    *,
    options: Any = None,
    initial_params: Optional[Dict[str, Any]] = None,
    **option_kwargs: Unpack[ScreenOptions]
) -> ScreenDef

Define a drawer screen. options may be a dict or (route) -> dict; keywords merge on top.

Navigator staticmethod

Navigator(
    *screens: ScreenDef,
    initial_route: Optional[str] = None,
    drawer_width: float = _DRAWER_WIDTH,
    key: Optional[str] = None
) -> Element

Render the drawer with the given screens (the first, or initial_route, shows first).

create_stack_navigator

create_stack_navigator() -> StackNavigator

Create a stack navigator: push and pop screens with history.

Stacks use native screen containers at every nesting level on mobile: UINavigationController on iOS and fragments on Android. The browser and headless renderer preserve the same logical screen ownership.

Example
import pythonnative as pn

Stack = pn.create_stack_navigator()

@pn.component
def App():
    return pn.NavigationContainer(
        Stack.Navigator(
            Stack.Screen("Home", HomeScreen, title="Home"),
            Stack.Screen("Detail", DetailScreen, title="Detail"),
        )
    )

create_tab_navigator

create_tab_navigator() -> TabNavigator

Create a tab navigator with a native tab bar.

Tabs stay mounted once visited (hidden while inactive) so switching back restores scroll position and state. Use lazy=False on a screen to mount it eagerly, or unmount_on_blur=True to tear it down when it loses focus.

Example
Tab = pn.create_tab_navigator()

Tab.Navigator(
    Tab.Screen("Home", HomeScreen, title="Home", tab_bar_icon="house"),
    Tab.Screen("Settings", SettingsScreen, title="Settings"),
)

create_drawer_navigator

create_drawer_navigator() -> DrawerNavigator

Create a drawer navigator: sibling screens behind a slide-in menu.

The handle returned by use_navigation inside a drawer screen is a DrawerNavigation with open_drawer(), close_drawer(), and toggle_drawer().

Container and deep linking

NavigationContainer: the root of a navigator tree.

The container wires the root navigator to the outside world: deep links (via LinkingConfig), a caller-supplied initial state, and on_state_change / on_ready callbacks. Every app with navigation renders exactly one container at the top.

Functions:

Name Description
NavigationContainer

Root of a navigator tree.

NavigationContainer

NavigationContainer(
    *children: Node,
    linking: Optional[LinkingConfig] = None,
    initial_state: Optional[StateLike] = None,
    on_state_change: Optional[
        Callable[[NavigationState], None]
    ] = None,
    on_ready: Optional[Callable[[], None]] = None
) -> Element

Root of a navigator tree.

Parameters:

Name Type Description Default
*children Node

The root navigator (a Stack.Navigator, Tab.Navigator, or Drawer.Navigator) and anything rendered alongside it.

()
linking Optional[LinkingConfig]

Deep-link configuration. The URL the app was launched with seeds the initial state; URLs that arrive later are dispatched as navigate calls.

None
initial_state Optional[StateLike]

Explicit initial state for the root navigator (a NavigationState or its to_dict() form). Takes precedence over the launch URL. State restored by a native host (a pushed native screen re-entering Python) takes precedence over both.

None
on_state_change Optional[Callable[[NavigationState], None]]

Called with the root navigator's state after every change. Persist state.to_dict() to restore later.

None
on_ready Optional[Callable[[], None]]

Called once the root navigator has mounted.

None
Example
Stack = pn.create_stack_navigator()

@pn.component
def App():
    return pn.NavigationContainer(
        Stack.Navigator(
            Stack.Screen("Home", HomeScreen),
            Stack.Screen("Detail", DetailScreen, options={"title": "Detail"}),
        ),
        linking=linking,
    )

Deep-link configuration: map URLs to navigation state and back.

linking = pn.LinkingConfig(
    prefixes=["myapp://", "https://example.com"],
    screens={
        "Home": "",
        "Detail": {"path": "item/:id", "parse": {"id": int}},
        "Tabs": {
            "path": "tabs",
            "screens": {"Feed": "feed", "Profile": "me/:user"},
        },
    },
)

Pass it to NavigationContainer and every URL the app opens with (cold start or while running) becomes a navigate on the root navigator. Each screen entry is either a path pattern ("item/:id", where :name segments capture params and the query string supplies the rest) or a dict with path, parse (per-param converters), and screens for a nested navigator.

Classes:

Name Description
LinkingConfig

URL <-> navigation state mapping for a navigator tree.

LinkingConfig

LinkingConfig(
    prefixes: Sequence[str],
    screens: Mapping[str, ScreenPathConfig],
)

URL <-> navigation state mapping for a navigator tree.

Parameters:

Name Type Description Default
prefixes Sequence[str]

URL prefixes this app answers to (schemes such as "myapp://" or web origins). Matching is case-insensitive and a trailing slash is optional.

required
screens Mapping[str, ScreenPathConfig]

Route name -> path pattern or nested config (see the module docstring).

required

Methods:

Name Description
strip_prefix

Return the path+query portion of url if it matches a prefix, else None.

state_from_url

Translate url into a (possibly nested) state, or None when nothing matches.

url_from_state

Build a URL for the focused leaf of state (None if it has no path).

strip_prefix

strip_prefix(url: str) -> Optional[str]

Return the path+query portion of url if it matches a prefix, else None.

state_from_url

state_from_url(url: str) -> Optional[NavigationState]

Translate url into a (possibly nested) state, or None when nothing matches.

url_from_state

url_from_state(state: NavigationState) -> Optional[str]

Build a URL for the focused leaf of state (None if it has no path).

Hooks

Hooks for reading navigation state from inside a screen.

Functions:

Name Description
use_navigation

Return the Navigation handle for the current screen.

use_route

Return the current screen's Route.

use_is_focused

Whether the calling component is on the focused screen.

use_focus_effect

Run effect while the screen is focused; its cleanup runs on blur.

use_navigation

use_navigation() -> Navigation

Return the Navigation handle for the current screen.

Raises:

Type Description
RuntimeError

When no navigator encloses the calling component.

Example
@pn.component
def HomeScreen():
    nav = pn.use_navigation()
    return pn.Button("Open", on_press=lambda: nav.navigate("Detail", id=42))

use_route

use_route() -> Route[Dict[str, Any]]
use_route(params_type: type[P]) -> Route[P]
use_route(params_type: Optional[type] = None) -> Route[Any]

Return the current screen's Route.

Pass a TypedDict class as params_type to get a Route[MyParams] whose params attribute is typed for editors and type checkers. At runtime the hook also verifies that every required key of the TypedDict is present on the active route, so a screen opened with the wrong params fails at its first render with a message naming the missing keys, instead of a KeyError deep inside the render.

Outside any navigator a placeholder route named "__root__" with empty params is returned (and no validation is performed), so components can be rendered standalone (previews, tests) without special-casing.

Parameters:

Name Type Description Default
params_type Optional[type]

Optional TypedDict describing this screen's params.

None

Raises:

Type Description
TypeError

If the active route is missing a required param declared by params_type.

Example
class DetailParams(TypedDict):
    id: int
    title: NotRequired[str]

@pn.component
def DetailScreen():
    route = pn.use_route(DetailParams)
    return pn.Text(f"Item {route.params['id']}")

use_is_focused

use_is_focused() -> bool

Whether the calling component is on the focused screen.

Combines the native host's lifecycle (a screen covered by a pushed native screen is not focused) with the in-tree state of declarative navigators (inactive tabs are not focused).

use_focus_effect

use_focus_effect(
    effect: Callable[[], Any],
    deps: Optional[Sequence[Any]] = None,
) -> None

Run effect while the screen is focused; its cleanup runs on blur.

Like use_effect, but the callback runs only when use_is_focused is True and re-runs each time the screen regains focus.

Parameters:

Name Type Description Default
effect Callable[[], Any]

Zero-arg callable, optionally returning a cleanup.

required
deps Optional[Sequence[Any]]

Extra dependencies (None re-runs on every focused render).

None
Example
@pn.component
def Feed():
    pn.use_focus_effect(lambda: refresh(), [])
    ...

The Navigation handle

The Navigation handle and the navigator core behind it.

Every screen rendered by a navigator receives a Navigation object through use_navigation. The handle is scoped to the screen's route (so add_listener("focus", ...) fires for that screen) and forwards every action to the NavigatorCore that owns the navigator's state.

Actions the core can't satisfy (an unknown route, popping past the first screen) bubble to the parent navigator, so a stack nested in a tab still pops correctly and navigate("Settings") from deep inside one tab can switch to another.

When the core belongs to the root stack of a native host it mutates its own state for pushes and pops: it asks the host to push or pop a real native screen carrying the serialized next state, and the new screen's navigator boots from that state.

Classes:

Name Description
HostNavigator

What a root stack needs from the native screen host.

NavigationEvent

Payload delivered to add_listener callbacks.

NavigatorCore

State machine shared by every Navigation handle a navigator hands out.

Navigation

Imperative navigation API for one screen.

TabNavigation

Handle for screens inside a tab navigator (adds jump_to).

DrawerNavigation

Handle for screens inside a drawer navigator (adds drawer controls).

Attributes:

Name Type Description
NavigationContext Context[Optional[Navigation]]

Provides the Navigation handle for the current screen.

FocusContext Context[bool]

Whether the current subtree is the focused screen (see use_is_focused).

NavigationContext module-attribute

NavigationContext: Context[Optional[Navigation]] = (
    create_context(None, name="Navigation")
)

Provides the Navigation handle for the current screen.

FocusContext module-attribute

FocusContext: Context[bool] = create_context(
    True, name="Focus"
)

Whether the current subtree is the focused screen (see use_is_focused).

HostNavigator

Bases: Protocol

What a root stack needs from the native screen host.

Hosts and FakeHost publish application focus and cached navigation state. Screen presentation belongs to the logical tree and its native containers.

Methods:

Name Description
initial_navigation_state

The serialized state this screen was pushed with, if any.

set_screen_options

Apply header options (title and friends) to the native bar.

add_focus_listener

Subscribe to the host covering / revealing this screen; returns an unsubscribe.

initial_navigation_state

initial_navigation_state() -> Optional[Dict[str, Any]]

The serialized state this screen was pushed with, if any.

set_screen_options

set_screen_options(options: Dict[str, Any]) -> None

Apply header options (title and friends) to the native bar.

add_focus_listener

add_focus_listener(
    callback: Callable[[bool], None],
) -> Callable[[], None]

Subscribe to the host covering / revealing this screen; returns an unsubscribe.

NavigationEvent

NavigationEvent(
    type_: str,
    route: Route,
    data: Optional[Mapping[str, Any]] = None,
)

Payload delivered to add_listener callbacks.

Attributes:

Name Type Description
type

"focus", "blur", "before_remove", or "state".

route

The route the event concerns.

data Dict[str, Any]

Extra event data (before_remove carries the action that caused it).

Methods:

Name Description
prevent_default

Cancel the action (only meaningful for before_remove).

prevent_default

prevent_default() -> None

Cancel the action (only meaningful for before_remove).

NavigatorCore

NavigatorCore(
    kind: NavigatorKind,
    screens: Mapping[str, ScreenDef],
    state: NavigationState,
    set_state: Callable[[Any], None],
    parent: Optional["Navigation"] = None,
    host: Optional[HostNavigator] = None,
    request_render: Optional[Callable[[], None]] = None,
)

State machine shared by every Navigation handle a navigator hands out.

Owned by the navigator component: created once per mount, updated every render with the latest state and setter (see update).

Methods:

Name Description
update

Sync the core with the owning component's latest render.

handle_for

The (cached) handle scoped to route.

route_by_key

Return the route with key, falling back to the active route once it has left the state.

options_for

Static screen options merged with any set_options overrides.

add_listener

Subscribe listener to event for the route with route_key; returns an unsubscribe callable.

emit

Deliver event to the listeners registered for route and return the event.

navigate

Go to the screen name: stacks pop back to it or push it; tabs and drawers jump to it.

push

Push a new instance of name with its initial_params merged under params.

replace

Swap the active screen for a fresh name (stacks); tabs and drawers fall back to navigate.

pop

Pop count screens. Returns whether anything was popped here or by a parent.

pop_to_top

Pop every screen above the first one (no-op when only one screen is present).

reset

Replace the whole history with routes, activating index (the last route by default).

set_params

Merge params into the route with route_key and commit the new state.

set_options

Merge runtime options for the route with route_key and request a render if anything changed.

set_drawer_open

Open or close the drawer (no-op unless a drawer navigator owns this core).

Attributes:

Name Type Description
is_native_root bool

Whether this core drives a native screen stack through the host.

is_native_root property

is_native_root: bool

Whether this core drives a native screen stack through the host.

update

update(
    screens: Mapping[str, ScreenDef],
    state: NavigationState,
    set_state: Callable[[Any], None],
    parent: Optional["Navigation"],
    host: Optional[HostNavigator],
) -> None

Sync the core with the owning component's latest render.

Handles and set_options overrides for routes no longer in state are dropped.

handle_for

handle_for(route: Route) -> 'Navigation'

The (cached) handle scoped to route.

route_by_key

route_by_key(key: str) -> Route

Return the route with key, falling back to the active route once it has left the state.

options_for

options_for(route: Route) -> Dict[str, Any]

Static screen options merged with any set_options overrides.

add_listener

add_listener(
    route_key: str, event: str, listener: Listener
) -> Callable[[], None]

Subscribe listener to event for the route with route_key; returns an unsubscribe callable.

emit

emit(
    route: Route,
    event: str,
    data: Optional[Mapping[str, Any]] = None,
) -> NavigationEvent

Deliver event to the listeners registered for route and return the event.

Check default_prevented on the result to see whether a before_remove listener cancelled the action.

navigate

navigate(
    name: str,
    params: Mapping[str, Any],
    nested: Optional[NavigationState] = None,
) -> None

Go to the screen name: stacks pop back to it or push it; tabs and drawers jump to it.

Unknown routes bubble to the parent navigator. On a native root stack, popping back is delegated to the host.

push

push(
    name: str,
    params: Mapping[str, Any],
    nested: Optional[NavigationState] = None,
) -> None

Push a new instance of name with its initial_params merged under params.

Non-stack navigators fall back to navigate; unknown routes bubble to the parent navigator.

replace

replace(
    name: str,
    params: Mapping[str, Any],
    nested: Optional[NavigationState] = None,
) -> None

Swap the active screen for a fresh name (stacks); tabs and drawers fall back to navigate.

pop

pop(count: int = 1, *, source: str = 'pop') -> bool

Pop count screens. Returns whether anything was popped here or by a parent.

pop_to_top

pop_to_top() -> None

Pop every screen above the first one (no-op when only one screen is present).

reset

reset(
    routes: Sequence[Route], index: Optional[int] = None
) -> None

Replace the whole history with routes, activating index (the last route by default).

Raises ValueError if any route name is unknown to this navigator.

set_params

set_params(
    route_key: str, params: Mapping[str, Any]
) -> None

Merge params into the route with route_key and commit the new state.

set_options

set_options(
    route_key: str, options: Mapping[str, Any]
) -> None

Merge runtime options for the route with route_key and request a render if anything changed.

set_drawer_open

set_drawer_open(open_: bool) -> None

Open or close the drawer (no-op unless a drawer navigator owns this core).

Navigation

Navigation(core: NavigatorCore, route_key: str)

Imperative navigation API for one screen.

Obtained with use_navigation. Every method that changes screens accepts the destination route name followed by params as keyword arguments:

nav.navigate("Detail", id=42)
nav.push("Detail", id=43)
nav.replace("Login")
nav.pop()
nav.pop_to_top()
nav.set_params(id=44)
nav.set_options(title="Edited")
unsubscribe = nav.add_listener("focus", lambda e: print("focused", e.route.name))

Unknown routes bubble to the parent navigator, so screens can navigate across nested navigators without knowing the tree shape.

Methods:

Name Description
get_params

Params of this handle's route.

get_state

The owning navigator's current state.

get_parent

The handle of the enclosing navigator, or None at the top.

get_options

Effective options for this handle's route (static merged with set_options).

can_go_back

Whether pop() would do anything (here or in a parent).

is_focused

Whether this handle's route is the navigator's active route.

navigate

Go to route: switch to it if already present, otherwise push it.

push

Push a new instance of route (stacks; tabs fall back to navigate).

replace

Replace the current screen with route.

pop

Pop count screens off the nearest stack; returns whether anything happened.

go_back

Alias for pop().

pop_to_top

Pop every screen above the first one.

reset

Replace the whole history.

set_params

Merge params into this handle's route.

set_options

Override ScreenOptions for this route at runtime.

add_listener

Subscribe to "focus", "blur", "before_remove", or "state" for this route.

Attributes:

Name Type Description
route Route

The route this handle belongs to.

kind NavigatorKind

"stack", "tab", or "drawer".

route property

route: Route

The route this handle belongs to.

kind property

kind: NavigatorKind

"stack", "tab", or "drawer".

get_params

get_params() -> Dict[str, Any]

Params of this handle's route.

get_state

get_state() -> NavigationState

The owning navigator's current state.

get_parent

get_parent() -> Optional['Navigation']

The handle of the enclosing navigator, or None at the top.

get_options

get_options() -> Dict[str, Any]

Effective options for this handle's route (static merged with set_options).

can_go_back

can_go_back() -> bool

Whether pop() would do anything (here or in a parent).

is_focused

is_focused() -> bool

Whether this handle's route is the navigator's active route.

navigate

navigate(
    route: str,
    /,
    *,
    screen: Optional[str] = None,
    **params: Any,
) -> None

Go to route: switch to it if already present, otherwise push it.

When route renders a nested navigator, screen names the screen to show inside it and params go to that screen:

nav.navigate("Tabs", screen="Profile", user="ada")

push

push(
    route: str,
    /,
    *,
    screen: Optional[str] = None,
    **params: Any,
) -> None

Push a new instance of route (stacks; tabs fall back to navigate).

replace

replace(
    route: str,
    /,
    *,
    screen: Optional[str] = None,
    **params: Any,
) -> None

Replace the current screen with route.

pop

pop(count: int = 1) -> bool

Pop count screens off the nearest stack; returns whether anything happened.

go_back

go_back() -> bool

Alias for pop().

pop_to_top

pop_to_top() -> None

Pop every screen above the first one.

reset

reset(
    *routes: Union[str, Route],
    index: Optional[int] = None,
    **params: Any
) -> None

Replace the whole history.

nav.reset("Home") installs a single route (params apply to it); nav.reset(Route("A"), Route("B", {...})) installs several, with index selecting the active one (last by default).

set_params

set_params(**params: Any) -> None

Merge params into this handle's route.

set_options

set_options(**options: Any) -> None

Override ScreenOptions for this route at runtime.

add_listener

add_listener(
    event: EventName, listener: Listener
) -> Callable[[], None]

Subscribe to "focus", "blur", "before_remove", or "state" for this route.

Returns an unsubscribe callable. before_remove listeners may call event.prevent_default() to keep the screen (useful for unsaved-changes prompts). Native back gestures on iOS can't be intercepted this way; use gesture_enabled=False to disable them for such screens.

TabNavigation

TabNavigation(core: NavigatorCore, route_key: str)

Bases: Navigation

Handle for screens inside a tab navigator (adds jump_to).

Methods:

Name Description
jump_to

Switch to the tab named route.

jump_to

jump_to(route: str, /, **params: Any) -> None

Switch to the tab named route.

DrawerNavigation

DrawerNavigation(core: NavigatorCore, route_key: str)

Bases: Navigation

Handle for screens inside a drawer navigator (adds drawer controls).

Methods:

Name Description
jump_to

Switch to the drawer screen named route and close the drawer.

open_drawer

Slide the drawer menu open.

close_drawer

Close the drawer menu.

toggle_drawer

Open the drawer menu if it's closed, otherwise close it.

is_drawer_open

Return whether the drawer menu is currently open.

jump_to

jump_to(route: str, /, **params: Any) -> None

Switch to the drawer screen named route and close the drawer.

open_drawer

open_drawer() -> None

Slide the drawer menu open.

close_drawer

close_drawer() -> None

Close the drawer menu.

toggle_drawer

toggle_drawer() -> None

Open the drawer menu if it's closed, otherwise close it.

is_drawer_open

is_drawer_open() -> bool

Return whether the drawer menu is currently open.

Screens and options

Screen definitions and the typed options a screen accepts.

Classes:

Name Description
ScreenOptions

Per-screen options accepted by Screen(...) and nav.set_options(...).

ScreenDef

Configuration for one screen inside a navigator.

Attributes:

Name Type Description
HeaderSlot

An element (or zero-arg factory) rendered into a header slot.

HeaderSlot module-attribute

HeaderSlot = Union[
    Element, Callable[[], Optional[Element]], None
]

An element (or zero-arg factory) rendered into a header slot.

ScreenOptions

Bases: TypedDict

Per-screen options accepted by Screen(...) and nav.set_options(...).

All keys are optional. Navigators ignore keys they don't use; the native host applies the header keys it can (see the platform notes on each key).

Attributes:

Name Type Description
title str

Screen title. Stack navigators show it in the native navigation bar; tab and drawer navigators use it as the item label.

header_shown bool

Whether the native navigation bar is visible for this screen (default True).

header_large_title bool

iOS: use a large title that collapses on scroll. Ignored elsewhere.

header_back_title str

iOS: label of the back button shown on the next screen when it navigates back to this one. Ignored elsewhere.

header_back_visible bool

Whether the back button is shown (default True).

header_left HeaderSlot

Element (or factory) rendered at the leading edge of the navigation bar. Rendered by PythonNative into the bar on iOS; ignored on Android and in the browser preview today.

header_right HeaderSlot

Element (or factory) rendered at the trailing edge of the navigation bar (same platform notes as header_left).

header_tint_color str

Color of the bar's buttons and back chevron.

header_style Dict[str, Any]

Style dict for the bar itself; background_color is honored on every platform that draws a bar.

header_title_style Dict[str, Any]

Style dict for the title label (color, font_size, bold).

presentation Literal['card', 'modal']

"card" (default) pushes; "modal" presents the screen as a sheet on iOS and as a full-screen push elsewhere.

gesture_enabled bool

Whether the interactive back gesture (iOS swipe) can pop this screen (default True).

animation Literal['default', 'none', 'fade', 'slide_from_right', 'slide_from_bottom']

Transition to use when the screen is pushed: "default", "none", "fade", "slide_from_right", "slide_from_bottom". Only "none" versus animated is distinguished on iOS and Android today.

tab_bar_icon Union[IconName, Asset]

Icon for the tab item: a bundled icon name from pythonnative.icons ("house", "settings") drawn as a vector on every platform, or a pn.asset pointing at a PNG that's drawn as a template image.

tab_bar_badge Union[str, int]

Badge text or count shown on the tab item.

tab_bar_label str

Label used for the tab item when it should differ from title.

lazy bool

Tab and drawer navigators only: mount the screen the first time it's focused (default True) instead of at navigator mount.

unmount_on_blur bool

Tab and drawer navigators only: unmount the screen when it loses focus instead of keeping it alive hidden (default False).

ScreenDef

ScreenDef(
    name: str,
    component: Callable[[], Any],
    *,
    options: Union[
        ScreenOptions, Callable[[Any], ScreenOptions], None
    ] = None,
    initial_params: Optional[Mapping[str, Any]] = None,
    **option_kwargs: Unpack[ScreenOptions]
)

Configuration for one screen inside a navigator.

Created by Navigator.Screen(name, component, **options).

Attributes:

Name Type Description
name

Route name used by nav.navigate(name).

component

The @component rendered when this screen is active. Receives no props; read params with use_route.

options Union[ScreenOptions, Callable[[Any], ScreenOptions]]

Static ScreenOptions for the screen. May be a callable (route) -> options to derive options from the route's params.

initial_params Dict[str, Any]

Params merged under any params supplied by navigate when this screen is first shown.

Methods:

Name Description
resolve_options

Return the static options, evaluating a callable options for route.

resolve_options

resolve_options(route: Any) -> Dict[str, Any]

Return the static options, evaluating a callable options for route.

State

Immutable navigation state and the pure operations on it.

A navigator's state is a NavigationState: an ordered tuple of Route entries plus the index of the active one. Stack navigators treat the tuple as a history (the active route is always the last); tab and drawer navigators keep one route per screen and move the index.

Every operation returns a new state, so navigators can store the state in use_state and diff it like any other value. States serialize to plain dicts (to_dict / from_dict) so a native host can hand a pushed screen the full history it belongs to.

Type Aliases:

Name Description
RouteParams

Bound for the P type parameter of Route.

Classes:

Name Description
Route

One entry in a navigator's state.

NavigationState

Immutable ordered routes plus the active index.

RouteParams

RouteParams = Mapping[str, Any]

Bound for the P type parameter of Route.

Declare a screen's params as a TypedDict and read them with use_route(MyParams) for a fully typed route.params.

Route

Route(
    name: str,
    params: Optional[Mapping[str, Any]] = None,
    key: Optional[str] = None,
    state: Optional["NavigationState"] = None,
)

One entry in a navigator's state.

Route is generic in its params type. Bare Route is Route[dict[str, Any]]; pass a TypedDict to use_route to get Route[MyParams] with a typed params attribute:

class DetailParams(TypedDict):
    id: int

route = pn.use_route(DetailParams)
route.params["id"]  # int

Attributes:

Name Type Description
name

The screen name this route renders.

params P

Parameters passed to the screen (read with use_route). Always a plain dict at runtime.

key

Stable identity for this particular visit to the screen, unique per process. Two pushes of the same screen have different keys, so their component state never mixes.

state

Seed state for a navigator rendered by this screen (set by navigate("Tabs", screen="Profile") and by deep links). None for ordinary screens.

Methods:

Name Description
with_params

Return a copy carrying params (merged over the current ones by default).

with_state

Return a copy carrying a nested navigator seed state.

to_dict

Serialize to a plain dict (name, params, key, and state when nested).

from_dict

Rebuild a route from to_dict output, keeping its key so component state carries over.

with_params

with_params(
    params: Mapping[str, Any], *, merge: bool = True
) -> "Route[P]"

Return a copy carrying params (merged over the current ones by default).

with_state

with_state(
    state: Optional["NavigationState"],
) -> "Route[P]"

Return a copy carrying a nested navigator seed state.

to_dict

to_dict() -> Dict[str, Any]

Serialize to a plain dict (name, params, key, and state when nested).

from_dict classmethod

from_dict(
    data: Mapping[str, Any],
) -> "Route[Dict[str, Any]]"

Rebuild a route from to_dict output, keeping its key so component state carries over.

NavigationState

NavigationState(
    routes: Iterable[Route], index: Optional[int] = None
)

Immutable ordered routes plus the active index.

Attributes:

Name Type Description
routes Tuple[Route, ...]

The routes, oldest first.

index

Position of the active route in routes.

Methods:

Name Description
find

Index of the most recent route named name, or None.

push

Append a new route and make it active (drops any forward entries).

pop

Remove up to count routes from the end (never below one).

pop_to_top

Keep only the first route.

pop_to

Pop back to the most recent route named name, merging params into it.

replace

Swap the active route for a fresh one (new key, so state resets).

navigate

Go to name: pop back to it if it's in the history, else push it.

jump_to

Activate the route named name in place, merging params.

set_params

Merge params into the active route.

reset

Return a state holding exactly routes with index active (the last route by default).

to_dict

Serialize to a plain dict with routes (each via Route.to_dict) and index.

from_dict

Rebuild a state from to_dict output; a missing index activates the last route.

current property

current: Route

The active route.

can_go_back property

can_go_back: bool

Whether a route precedes the active one.

find

find(name: str) -> Optional[int]

Index of the most recent route named name, or None.

push

push(
    name: str,
    params: Optional[Mapping[str, Any]] = None,
    state: Optional["NavigationState"] = None,
) -> "NavigationState"

Append a new route and make it active (drops any forward entries).

pop

pop(count: int = 1) -> 'NavigationState'

Remove up to count routes from the end (never below one).

pop_to_top

pop_to_top() -> 'NavigationState'

Keep only the first route.

pop_to

pop_to(
    name: str,
    params: Optional[Mapping[str, Any]] = None,
    state: Optional["NavigationState"] = None,
) -> "NavigationState"

Pop back to the most recent route named name, merging params into it.

replace

replace(
    name: str,
    params: Optional[Mapping[str, Any]] = None,
    state: Optional["NavigationState"] = None,
) -> "NavigationState"

Swap the active route for a fresh one (new key, so state resets).

navigate

navigate(
    name: str,
    params: Optional[Mapping[str, Any]] = None,
    state: Optional["NavigationState"] = None,
) -> "NavigationState"

Go to name: pop back to it if it's in the history, else push it.

jump_to

jump_to(
    name: str,
    params: Optional[Mapping[str, Any]] = None,
    state: Optional["NavigationState"] = None,
) -> "NavigationState"

Activate the route named name in place, merging params.

set_params

set_params(params: Mapping[str, Any]) -> 'NavigationState'

Merge params into the active route.

reset

reset(
    routes: Sequence[Route], index: Optional[int] = None
) -> "NavigationState"

Return a state holding exactly routes with index active (the last route by default).

to_dict

to_dict() -> Dict[str, Any]

Serialize to a plain dict with routes (each via Route.to_dict) and index.

from_dict classmethod

from_dict(data: Mapping[str, Any]) -> 'NavigationState'

Rebuild a state from to_dict output; a missing index activates the last route.

Host bridge

Bridge between the native screen host and the navigation tree.

The host wraps the app's root element in HostRoot, which publishes:

Pushed screens receive their navigation history under the "pn_nav" key of the host's launch arguments; the root stack reads it through HostNavigator.initial_navigation_state.

Functions:

Name Description
HostRoot

Publish the host bridge and its focus state to the tree below.

Attributes:

Name Type Description
NAV_STATE_ARG

Launch-argument key under which a pushed screen receives its serialized navigation state.

HostContext Context[Optional[HostNavigator]]

The native host bridging this tree, or None when rendering without one (tests, rows).

NAV_STATE_ARG module-attribute

NAV_STATE_ARG = 'pn_nav'

Launch-argument key under which a pushed screen receives its serialized navigation state.

HostContext module-attribute

HostContext: Context[Optional[HostNavigator]] = (
    create_context(None, name="Host")
)

The native host bridging this tree, or None when rendering without one (tests, rows).

HostRoot

HostRoot(*children: Node, host: HostNavigator) -> Element

Publish the host bridge and its focus state to the tree below.

initial_state_from_args

initial_state_from_args(
    args: Optional[Dict[str, Any]],
) -> Optional[Dict[str, Any]]

Extract a serialized navigation state from host launch arguments.

Next steps