Skip to main content

Tree Props

The Types of Props page details different types of Litho props. This page covers one more type of props - Tree Props.

Tree Props​

note

A tree prop is a special type of prop that is transparently passed from a parent component to its children.

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 Installing 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 installed via the TreePropProvider API

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

legacyTreePropOf API enables interop with the old class-based system of declaring TreeProps and may be declared inline at installation site. 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

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.