Components
What is a component?β
Components are the fundamental building blocks of UIs in Litho. They consist of a render function that can use the component's props and state to configure and return other components. The returned components are further resolved by recursively calling render
on them until the process results in primitives like Text
or Image
, which can be positioned and materialized on the screen.
The following example shows a component that takes a name as a prop and renders a greeting with a Text
component.
class HelloComponent(private val name: String) : KComponent() {
override fun ComponentScope.render(): Component {
return Text(text = "Hello $name!")
}
}
If you need to integrate your own views/drawables with Litho, please see Primitive Components
What's the relationship between a component and a view?
In practice, a component is just a type and a bag of props and is cheap to instantiate. Instantiating a component does not instantiate a View. At mount time, only primitive components that mount Views or have View properties (such as viewTag
) will materialize Views in the final layout.
Declaring a Componentβ
A component is declared as a simple sub-class of KComponent
, overriding a single function: render
. You can declare the props a component takes as standard val
properties; as is normal in Kotlin, these may be declared as optional by providing a default value.
To instantiate an existing component, specify the props in the constructor of that component. By convention, named arguments are used for clarity, even if the prop is required:
Text(text = "Hello $name!")
Note that KComponents are only supported in Kotlin; if you need to declare a component from Java, look at the legacy Spec API.
Rules for componentsβ
For correctness, Litho components must follow two functional-programming rules:
- Components must be immutable - they only support
val
properties (novar
properties!). Components are re-used across threads, so mutability can introduce subtle but aggravating correctness issues. render
must be a pure function without side-effects - if render is called with the same props and state, it should always return the same result without modifying other app state.
Other ways to configure componentsβ
Following are some other ways you can affect your component's rendering:
- Common Props - uses the
Style
object to configure built-in behavior on a component, like click handling and background color. - Tree Props - provides a way to give access to contextual objects, like a theme or logging utility, to all components in a sub-tree without having to manually pass them.
- State - allows a component to persist private state across updates to the tree.