Raxol.UI.Components.Base.Component behaviour (Raxol v0.2.0)
View SourceDefines the behavior for UI components in the Raxol system.
This module provides the core structure for building reusable UI components with lifecycle hooks, state management, and event handling. Components follow a similar pattern to the main application architecture but at a smaller scale.
Component Lifecycle
init/1
- Initialize component state with propsmount/1
- Called when the component is first mountedupdate/2
- Handle messages and update component staterender/1
- Generate the visual representation of the componenthandle_event/2
- Handle UI eventsunmount/1
- Clean up resources when component is removed
Example
defmodule MyComponent do
use Raxol.UI.Components.Base.Component
def init(props) do
Map.merge(%{count: 0}, props)
end
def mount(state) do
{state, []}
end
def update(:increment, state) do
%{state | count: state.count + 1}
end
def render(state) do
row do
button(label: "-", on_click: :decrement)
text("Count: #{state.count}")
button(label: "+", on_click: :increment)
end
end
def handle_event({:click, :increment}, state) do
{update(:increment, state), []}
end
def handle_event({:click, :decrement}, state) do
{%{state | count: state.count - 1}, []}
end
end
Summary
Callbacks
Handles UI events that occur on the component.
Initializes the component with the given props.
Called when the component is mounted in the UI.
Renders the component based on its current state.
Called when the component is being removed from the UI.
Updates the component state in response to messages.
Types
Callbacks
Handles UI events that occur on the component.
The context map provides additional event details or UI state. Returns the potentially modified state and any commands to execute.
Initializes the component with the given props.
Called when the component is created. Should merge default values with the provided props to create the initial state.
Called when the component is mounted in the UI.
This is where you can set up subscriptions, execute initial commands, or perform other setup tasks. Returns the potentially modified state and any commands to execute.
Renders the component based on its current state.
Returns an element tree that will be rendered to the screen. The context map contains theme, layout constraints, etc.
Called when the component is being removed from the UI.
Use this to clean up any resources or perform final actions.
Updates the component state in response to messages.
Similar to the application update function, this handles messages sent to the component and returns the new state.