Overview
NavigationLink(state:) is a SwiftUI view initializer that integrates with The Composable Architecture’s stack-based navigation. It allows you to create navigation links that push new state onto a StackState collection when tapped.
This is the primary way to navigate to new screens in stack-based navigation with TCA.
Usage
Basic Navigation
Create a navigation link by providing the state to push onto the stack:With NavigationStack
Use withNavigationStack and a binding to the store’s path:
Complete Example
Passing Data to Child
You can pass data from the parent to the child state:Custom Label
Use the trailing closure syntax for custom labels:How It Works
- When a
NavigationLink(state:)is tapped, it sends aStackAction.pushaction to the store - The action includes both an auto-generated ID and the state to push
- The
forEachreducer operator intercepts this action and appends the state to theStackState - SwiftUI’s
NavigationStackobserves the change and pushes the new screen - The destination closure renders the appropriate view based on the state
Key Points
- Type-Safe: The state must match the type expected by the
StackState - Automatic IDs: Stack element IDs are generated automatically
- Declarative: Navigation is driven entirely by state changes
- Deep Links: You can programmatically append multiple states to navigate deep into the stack
Related Types
StackState- Collection type for managing navigation stack stateStackAction- Action wrapper for stack-based navigationforEach- Reducer operator for stack stateStackElementID- Identifier for stack elements