0
# Components and Decorators
1
2
Core functionality for defining ReactPy components with proper lifecycle management and rendering. Components are the fundamental building blocks of ReactPy applications, created using the `@component` decorator.
3
4
## Capabilities
5
6
### Component Decorator
7
8
The `@component` decorator transforms a regular Python function into a ReactPy component that can manage state and participate in the rendering lifecycle.
9
10
```python { .api }
11
@component
12
def component_function(*args, key: Any | None = None, **kwargs) -> ComponentType | VdomDict | str | None: ...
13
```
14
15
**Parameters:**
16
- `function`: The component's render function that returns VDOM, string, or None
17
- `key`: Optional key for component identity in lists (passed as keyword argument)
18
19
**Returns:** A constructor function that creates Component instances
20
21
**Usage Examples:**
22
23
```python
24
from reactpy import component, html
25
26
@component
27
def HelloWorld(name: str = "World"):
28
return html.h1(f"Hello, {name}!")
29
30
@component
31
def Button(text: str, on_click=None):
32
return html.button({"onClick": on_click}, text)
33
34
# Usage with key for lists
35
items = ["Apple", "Banana", "Cherry"]
36
fruit_buttons = [
37
Button(item, key=item)
38
for item in items
39
]
40
```
41
42
### Component Class
43
44
The Component class represents an instantiated component with rendering capabilities and metadata.
45
46
```python { .api }
47
class Component:
48
key: Any | None
49
type: Callable[..., ComponentType | VdomDict | str | None]
50
51
def __init__(
52
self,
53
function: Callable[..., ComponentType | VdomDict | str | None],
54
key: Any | None,
55
args: tuple[Any, ...],
56
kwargs: dict[str, Any],
57
sig: inspect.Signature,
58
) -> None: ...
59
60
def render(self) -> ComponentType | VdomDict | str | None: ...
61
```
62
63
**Attributes:**
64
- `key`: Component key for identity tracking in lists
65
- `type`: The original component function
66
67
**Methods:**
68
- `render()`: Execute the component function with its arguments to produce VDOM
69
70
### Component Patterns
71
72
**Functional Components:**
73
```python
74
@component
75
def Counter():
76
count, set_count = use_state(0)
77
return html.div(
78
html.p(f"Count: {count}"),
79
html.button({"onClick": lambda: set_count(count + 1)}, "Increment")
80
)
81
```
82
83
**Components with Props:**
84
```python
85
@component
86
def UserCard(name: str, email: str, avatar_url: str = None):
87
return html.div(
88
html.img({"src": avatar_url}) if avatar_url else None,
89
html.h3(name),
90
html.p(email)
91
)
92
```
93
94
**Components with Children:**
95
```python
96
@component
97
def Card(*children, title: str = None):
98
return html.div(
99
{"className": "card"},
100
html.h2(title) if title else None,
101
html.div({"className": "card-body"}, *children)
102
)
103
```
104
105
**Conditional Rendering:**
106
```python
107
@component
108
def ConditionalComponent(show_content: bool = True):
109
if not show_content:
110
return html.p("No content to display")
111
112
return html.div(
113
html.h1("Content"),
114
html.p("This is the main content")
115
)
116
```
117
118
### Error Handling
119
120
Components may raise TypeError if using reserved parameter names:
121
122
```python
123
# This will raise TypeError
124
@component
125
def invalid_component(key: str): # 'key' is reserved
126
return html.div(key)
127
```
128
129
The `key` parameter is reserved for component identity and cannot be used as a regular parameter in component functions.