OneScript

NavigationStack

Push and pop pages driven by a path.

NavigationStack renders a native SwiftUI navigation stack. Its children are the root page, and each value in the path is rendered as a pushed page by destination.

import { app } from "onescript"
import { Modifier, NavigationLink, NavigationStack, Text, VStack } from "onescript/views"

function Detail(props: { id: string }) {
  return (
    <Text modifier={Modifier.navigationTitle(`Item ${props.id}`)}>
      Detail of {props.id}
    </Text>
  )
}

await app.show(
  <NavigationStack destination={(id: string) => <Detail id={id} />}>
    <VStack
      spacing={12}
      modifier={Modifier.navigationTitle("Items")}
    >
      <NavigationLink value="a">Open A</NavigationLink>
      <NavigationLink value="b">Open B</NavigationLink>
    </VStack>
  </NavigationStack>
)

Controlled path

Pass path and onPathChange to own the navigation state. Assign a new array to push, pop, or jump to several pages at once. When the user taps Back or swipes back, OneScript calls onPathChange with the shortened path.

import { Button, NavigationStack, Text, VStack, useState } from "onescript/views"

function App() {
  const [path, setPath] = useState<number[]>([])

  return (
    <NavigationStack
      path={path}
      onPathChange={setPath}
      destination={id => (
        <VStack spacing={12}>
          <Text>Page {id}</Text>
          <Button action={() => setPath([...path, id + 1])}>Next</Button>
          <Button action={() => setPath([])}>Back to root</Button>
        </VStack>
      )}
    >
      <Button action={() => setPath([1])}>Start</Button>
    </NavigationStack>
  )
}
PropTypeDescription
childrenViewChildThe root page.
destination(value: T) => ViewChildRenders the page for each path value. Required when the path is not empty. Hooks can be used inside the returned components.
pathT[]Optional controlled path. T is string | number.
onPathChange(path: T[]) => voidCalled when the path changes. Required with path.

Behavior

  • NavigationStack must be the root view passed to app.show(), the only direct content of a Tab, or the content of a sheet, fullScreenCover, or popover, and cannot be nested. Applying presentation modifiers to a NavigationStack in these positions is fine.
  • Each page is identified by its position and value. Replacing a value rebuilds that page and resets its state, while the pages below it keep their state.
  • The Close and Console buttons appear on the root page only. Pushed pages show the system Back button.
  • When the root page does not set navigationTitle, the project name is used as the title. navigationTitle can't be applied to NavigationStack itself; apply it to the views inside each page.
  • Apply toolbar to views inside the stack. Applying it to NavigationStack itself throws an error.

How is this guide?

Last updated on

On this page