Elements

Elements

Host elements are the lowercase JSX tags: <view>, <text>, <image> and the rest. Each one is a native view (a UIView subclass on iOS and Mac Catalyst, an Android View), created and laid out by the nsh runtime. Everything an app shows is made of them: the components of nsh/ui/mobile are drawn with the same elements.

import { mount, signal } from "nsh";

function App() {
  const count = signal(0);
  return (
    <view style={{ flex: 1, alignItems: "center", justifyContent: "center", gap: 12 }}>
      <text style={{ fontSize: 24 }}>Tapped {count()} times</text>
      <view onPress={() => count.update((n) => n + 1)} activeOpacity={0.6} class="rounded-lg bg-blue-600 px-4 py-2">
        <text class="text-white">Tap</text>
      </view>
    </view>
  );
}

mount(App);

Built-in tags need no import. Capitalized tags are components; a component in scope may also be written in kebab case (Button as <button>), and an app’s binding wins over a built-in of the same name: importing Modal from nsh/ui/mobile makes <modal> that component. See JSX and components.

#All elements

TagNative view (iOS / Android)Typed componentPage
<view>UIView / ViewGroupview
<text>CoreText view / StaticLayout viewtext
<image>a view with an image layer / an image viewimage
<scroll>UIScrollView / ScrollViewscroll
<input>UITextField or UITextView / EditTextinput
<list>UIScrollView / ScrollView with recycled cellsList (nsh/list)list
<canvas>a view replaying a 2D drawingCanvas (nsh/canvas)canvas
<web-view>WKWebView / android.webkit.WebViewWebView (nsh/webview)web-view
<video>AVPlayerLayer / MediaPlayer on a TextureViewVideo (nsh/video)video
<modal>presented view controller / DialogModal (nsh/ui/mobile)modal
<input-accessory>a bar over the keyboard (iOS only)InputAccessoryView (nsh/ios)nsh/ios
<if>, <each>none: control flowcontrol flow

The tags without a typed form of their own (<canvas>, <web-view>, <video>, <modal>, <input-accessory>) accept any prop in TypeScript. Prefer their components: those are typed and add what the bare tag lacks (a draw function, a visible prop, safe-area insets).

#Common props

Every host element accepts the props below (the CommonProps type). Element pages list only their own props.

#Styling

PropTypeDescription
styleStyleProp<ViewStyle> (TextStyle for <text> and <input>, ImageStyle for <image>)Inline style, or an array of styles merged left to right (falsy entries skipped). Wins over class. See the style reference.
classstringTailwind classes, resolved natively ("flex-row gap-2 p-4 dark:bg-zinc-900"). Later classes win over earlier ones. See Tailwind.
classListRecord<string, boolean | null | undefined>Classes applied while their value is truthy ({ "opacity-50": busy() }).
disabledbooleanIgnores presses (no press feedback either), applies disabled: classes and disables controls such as inputs.

#Presses and feedback

Press handling runs natively: the platform recognizes the press and shows the feedback, and JS only hears about it afterwards. Only the innermost pressable view responds; inside scroll views a press-in waits about 130 ms so a scroll can start first.

PropTypeDefaultDescription
onPress() => voidA tap ended inside the view.
onLongPress() => voidThe finger stayed down for delayLongPress.
onPressIn() => voidA finger went down on the view.
onPressOut() => voidThe finger lifted or left.
delayLongPressnumber500Milliseconds before a press becomes a long press.
activeOpacitynumberThe view’s opacity while pressed.
underlayColorColorValueThe background while pressed; the children fade to underlayOpacity.
underlayOpacitynumber0.85The children’s opacity while underlayColor shows.
hitSlopnumber | { top?, right?, bottom?, left? }Extends the touch area beyond the bounds, in points.
pointerEvents"auto" | "none" | "box-none" | "box-only""auto"Which touches the view and its children receive (React Native semantics).

active: Tailwind classes also apply while a view is pressed, with no JS round trip.

#Layout and identity

PropTypeDescription
onLayout(e: LayoutEvent) => voidThe view’s frame relative to its parent, { x, y, width, height }, after each layout that changes it.
refYNode | (node: YNode) => voidThe native node (see ref methods). ref={el} assigns a variable, ref={fn} calls a function.
nativeIDstringNames the view for others, e.g. the InputAccessoryView an input refers to.
testIDstringAn identifier for UI tests (on Android, the view’s resource id).

#Gestures driving native values

These props bind a gesture to native animated values that move on the UI thread, with no JS per frame. See touch and gestures.

PropTypeDescription
pan{ x?: NativeValue; y?: NativeValue }Drags drive these values (points).
onPanStart(e: PanEvent) => voidA drag started.
onPanEnd(e: PanEvent) => voidA drag ended, with the release velocity (e.g. to start a decay).
pinch{ scale?: NativeValue }Two-finger pinches drive scale.
onPinchStart / onPinchEnd(e: { scale: number; velocity: number }) => voidA pinch started / ended.
rotation{ angle?: NativeValue }Two-finger rotations drive angle (degrees).
onRotationStart / onRotationEnd(e: { rotation: number; velocity: number }) => voidA rotation started / ended.

PanEvent is { translationX, translationY, velocityX, velocityY, valueX?, valueY? }: the translation since the start, the velocity in points per second, and the bound values at that moment (a drag can grab a value mid-animation).

#Raw touches and the responder system

For gestures the props above do not cover, every element takes React Native’s touch and responder props: onTouchStart, onTouchMove, onTouchEnd, onTouchCancel (and their …Capture forms), onStartShouldSetResponder, onMoveShouldSetResponder (and …Capture), onResponderGrant, onResponderReject, onResponderStart, onResponderMove, onResponderEnd, onResponderRelease, onResponderTerminate and onResponderTerminationRequest. Each handler gets a GestureResponderEvent ({ identifier, locationX, locationY, pageX, pageY, target, timestamp, touches, changedTouches, nativeEvent, stopPropagation() }). Returning true from onResponderGrant keeps native scroll views from taking the touches. PanResponder in nsh/gesture builds on them.

#Accessibility

PropTypeDescription
accessiblebooleanThe view is one element for assistive technologies; its children are not exposed separately.
accessibilityLabelstringWhat screen readers read. Views without a label read their texts.
accessibilityHintstringWhat activating the element does.
accessibilityRole / roleAccessibilityRoleWhat the element is ("button", "header", "link", "switch", …).
accessibilityState{ disabled?, selected?, checked?, busy?, expanded? }The state assistive technologies report (checked may be "mixed").
accessibilityValue{ min?, max?, now?, text? }The value of a range or textual element.
accessibilityElementsHiddenbooleanHides the view and its subtree from assistive technologies.
importantForAccessibility"auto" | "yes" | "no" | "no-hide-descendants"Whether the view is exposed.
accessibilityActions{ name: string; label?: string }[]Custom actions offered to assistive technologies.
onAccessibilityAction(e: { actionName: string }) => voidThe user invoked one of accessibilityActions.

See accessibility.

#Platform-only props

Props that exist on one platform go in an object named after it, so the shared props stay the same everywhere. Only the current platform’s object is sent; the others are ignored.

PropDescription
ios={{…}}iOS and Mac Catalyst. <input>, Modal and WebView add their own keys.
android={{…}}Android. Every element takes ripple, elevation and accessibilityLiveRegion (below).
desktop={{…}}Desktop platforms; ignored on mobile.
android keyTypeDescription
ripple{ color?, borderless?, radius?, foreground? }The material ripple while pressed.
elevationnumberThe material shadow (points), from the view’s shape.
accessibilityLiveRegion"none" | "polite" | "assertive"How changes of the view are announced to TalkBack.
<view onPress={save} android={{ ripple: { color: "#00000022" }, elevation: 2 }} class="rounded-lg bg-white p-4">
  <text>Save</text>
</view>

See platform-specific code.

#Ref methods

ref receives a YNode. Its methods send commands to the native view, in order with the changes made before them in the same turn. Each element page says which apply to it.

MethodApplies toDescription
focus() / blur()<input>Focuses (shows the keyboard) / unfocuses.
setSelection(start, end?)<input>Selects start..end in UTF-16 units; a caret without end.
scrollTo({ x?, y?, animated? })<scroll>, ListScrolls to an offset.
zoomTo({ scale, x?, y?, animated? })zoomable <scroll>Zooms to scale around a content point.
scrollToOffset({ offset, animated? })ListScrolls to an offset along the list’s axis.
scrollToIndex({ index, animated?, viewPosition?, viewOffset? })ListScrolls an item into view.
scrollToEnd({ animated? })ListScrolls to the end of the content.
reload(), goBack(), goForward(), stopLoading(), injectJavaScript(script), postMessage(data)WebViewControls the page.
seek(seconds)VideoJumps to a time.
command(name, args?)native componentsCalls a command of a registered native component (nsh/native).
import { type YNode } from "nsh";

let input!: YNode;
<view onPress={() => input.focus()}>
  <input ref={input} placeholder="Tap the row to type" />
</view>;

#Why handlers never block the UI

The main thread never waits for JS. When the system needs an answer on the spot (may this text change, may the back button pop, may this sheet close), nsh answers it natively from props set beforehand (maxLength, preventBack, dismissible, pointerEvents, …), and the event reaches JS afterwards. This is why such behavior is a prop, not a return value of a handler.