Content will be updated
This page was moved from the old website without any change and might be updated
A TreeProp is a special type of prop which 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
to every component in your hierarchy.
A good candidate, for example, is a prefetcher which fetches network images
ahead of render time. The prefetcher is widely used since images are common. The
prefetcher implementation might be something we define for any Component that
needs to use it without having to pass it as
@Prop in the entire tree.
Each TreeProp is declared and created from a method annotated with
You can only declare one TreeProp for any one given type. If a child of ParentComponent also defines a TreeProp of type Prefetcher, it will override the value of that TreeProp for all its children (but not for itself).
The child component can access the TreeProp value through a param annotated with TreeProp that has the same type as that which was declared in the parents @OnCreateTreeProp method.
Once created, the TreeProp value will be passed down to all children, but will not be accessible from the component that created this TreeProp.
If you want to access a TreeProp from the component that created this TreeProp, you can transform it into
@State value like this:
ImportantHelper instance is accessible as
@State as usual:
TreeProps can be used in both Components and Sections and even shared and modified between them. Let's consider the example of a logging datastructure we pass down from the root component to capture information about the hierarchy.
Immutable TreeProps are easier to reason about, so try to follow that design pattern whenever possible.
We now create a component hierarchy that looks like this:
We start by setting up the RootComponent and the RecyclerComponent sitting inside:
The TopGroupSection takes in the root TreeProp and adds its "top" tag to it.
We're omitting the bottom part here for brevity, but you can find it in the repository under instrumentation-tests.
The leaf node simply renders the TreeProp as text in our example case here, but would normally perform some sort of logging based on the context.
The result on screen will be three rows of text that read
This illustrates how TreeProps propagate through both component and section trees and can be used to selectively share information with their children.