Skip to main content

Tree Props

A TreeProp is a special type of prop which is transparently passed from a parent component to its children. It provides a convenient way to share contextual data or utilities in a tree without having to explicitly pass val properties to every component in your hierarchy.

Declaring and Providing a Tree Prop​

TreeProps must first be declared using reusable Kotlin properties.

val typefaceTreeProp: TreeProp<Typeface> = treePropOf { error("No default value supplied") }
val titleTreeProp: TreeProp<String?> = legacyTreePropOf()

Afterwards, they may be provided via the TreePropProvider API

return TreePropProvider(
typefaceTreeProp to Typeface.DEFAULT_BOLD,
titleTreeProp to getTextTitle(),
legacyTreePropOf<Int>() to Color.RED,
) {
TreePropsChildComponent()
}

Using a Tree Prop​

The child component can access the TreeProp value by invoking the value of a previously declared TreeProp. In addition, child components may also use the ComponentScope.getTreeProp<>() method for interop with the legacy system.

val typeface = typefaceTreeProp.value
val title = titleTreeProp.value
val color = getTreeProp<Int>()

When to Use Tree Props​

Tree Props are powerful, but if overused, they can make your component code more difficult to understand. The best practice is to only use tree props for properties that the whole tree needs to know about (such as theming information or loggers) and not just as a more convenient way to get props to the leaves of a tree of components.

Legacy TreeProps and Interop with the Spec API​

legacyTreePropOf API enables interop with the old class-based system of declaring TreeProps from the Java Spec API. While it's still possible to use T::class.java directly, it is highly discouraged as it may introduce subtle bugs arising from Kotlin's strict type system, especially with primitives.

note

The legacy APIs allow declaring one TreeProp for any one given type. If a child of ParentComponent also defines a TreeProp of the given type, it will override the value of that TreeProp for all its children (but not for itself).

This limitation does not apply to the treePropOf API