### Install reactpy-django
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/learn/add-reactpy-to-a-django-project.md
Installs the reactpy-django package using pip. This is the first step to integrate ReactPy into your Django project.
```bash
pip install reactpy-django
```
--------------------------------
### Example ReactPy Component (Python)
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/learn/add-reactpy-to-a-django-project.md
A basic example of a Python file defining a ReactPy component, intended to be rendered within a Django template.
```python
from reactpy import html
@reactpy.component
def my_component():
return html.div("Hello, ReactPy!")
```
--------------------------------
### Install channels-redis for Django
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/hooks.md
This bash command installs the 'channels-redis' package, a Redis implementation for Django Channels. This is a prerequisite for using Redis as your channel layer backend in Django.
```bash
pip install channels-redis
```
--------------------------------
### Example Django Template Integration (HTML)
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/learn/add-reactpy-to-a-django-project.md
An example of a Django HTML template that includes a ReactPy component using the reactpy_django template tag.
```html
{% load reactpy %}
ReactPy in Django
{% react_component my_component %}
```
--------------------------------
### Run Django database migrations
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/learn/add-reactpy-to-a-django-project.md
Executes Django's migrate command to set up any necessary database tables for ReactPy-Django.
```bash
python manage.py migrate
```
--------------------------------
### Add Python Dependencies to PyScript Setup
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
Demonstrates how to specify additional Python dependencies for PyScript using the `pyscript_setup` tag in a Jinja template. Dependencies are listed in Python requirements file syntax and are automatically installed client-side.
```jinja
{% include "../../examples/html/pyscript_setup_dependencies.html" %}
```
--------------------------------
### Install webtypy for PyScript Type Hints
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
Command to install the `webtypy` package, which provides type hints for PyScript components within your editor, enhancing development experience.
```bash
pip install webtypy
```
--------------------------------
### Check Django configuration
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/learn/add-reactpy-to-a-django-project.md
Runs Django's check command to verify that ReactPy-Django and other project configurations are set up correctly.
```bash
python manage.py check
```
--------------------------------
### Configure INSTALLED_APPS in settings.py
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/learn/add-reactpy-to-a-django-project.md
Adds 'reactpy_django' to the INSTALLED_APPS setting in Django's settings.py file to enable the package.
```python
INSTALLED_APPS = [
# ... other apps
"reactpy_django",
]
```
--------------------------------
### Configure Channels INSTALLED_APPS in settings.py
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/learn/add-reactpy-to-a-django-project.md
Adds 'daphne' to the INSTALLED_APPS setting for Django Channels and ASGI support, which is required by ReactPy-Django.
```python
INSTALLED_APPS = [
# ... other apps
"daphne",
]
```
--------------------------------
### Include PyScript Setup in HTML Template
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
This Jinja template snippet includes the necessary PyScript setup file for a given HTML page. It ensures that PyScript is correctly configured to run within the page.
```jinja
{% include "../../examples/html/pyscript_setup.html" %}
```
--------------------------------
### Python: Use Mutation Hook Example
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/hooks.md
Demonstrates the basic usage of the useMutation hook for modifying data in the Django ORM. This example shows how to define and call a mutation function.
```python
from reactpy import html, use_state
from reactpy.core.hooks import use_mutation, use_query
def todo_list():
items, _ = use_query(get_items)
add_item, delete_item = use_mutation(
mutation=add_item_mutation, refetch=get_items
)
return html.div(
html.ul([
html.li(item["text"]) for item in items
]),
html.button({"on_click": lambda: add_item(text="New Item")}, "Add Item"),
)
def get_items():
return TodoItem.objects.all().values()
def add_item_mutation(text):
TodoItem.objects.create(text=text)
```
--------------------------------
### PyScript Component Example (HTML)
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/html.md
An example of an HTML template that utilizes the PyScript component. This template demonstrates how to include Python code execution within an HTML file using the PyScript tag, which is managed by ReactPy Django.
```html
PyScript Example
print('Hello from PyScript!')
This is a regular HTML paragraph.
```
--------------------------------
### Configure ASGI_APPLICATION in settings.py
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/learn/add-reactpy-to-a-django-project.md
Sets the ASGI_APPLICATION variable in settings.py to point to your project's ASGI application, enabling asynchronous request handling for ReactPy.
```python
ASGI_APPLICATION = "your_project.asgi.application"
```
--------------------------------
### Configure REACTPY_WEBSOCKET_ROUTE in asgi.py
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/learn/add-reactpy-to-a-django-project.md
Registers ReactPy's WebSocket route in your project's asgi.py file, enabling real-time communication for interactive components.
```python
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project.settings")
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(URLRouter([])),
})
# ReactPy specific websocket route
REACTPY_WEBSOCKET_ROUTE = "websocket"
```
--------------------------------
### Basic PyScript Hello World Component
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
A simple Python component for PyScript that serves as a 'Hello, World!' example. This component is designed to run directly in the browser and requires a `#!python def root()` function as its entry point.
```python
{% include "../../examples/python/pyscript_hello_world.py" %}
```
--------------------------------
### Python Example for Config Object
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
This Python view function demonstrates how to pass a dictionary representing PyScript configuration to an HTML template. It shows how to dynamically set PyScript's behavior from the Django backend.
```python
{% include "../../examples/python/pyscript_setup_config_object.py" %}
```
--------------------------------
### Initialize PyScript Setup in Django Template
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
Provides the necessary Jinja template code to initialize PyScript within a Django template. This is a prerequisite for using PyScript components. The `pyscript_setup` tag ensures that PyScript is properly loaded and configured on the client-side before any PyScript components are rendered.
```jinja
{% load pyapp %}
PyScript Setup Example
{% pyscript_setup %}
PyScript is set up!
```
--------------------------------
### Configure urlpatterns in urls.py
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/learn/add-reactpy-to-a-django-project.md
Includes ReactPy's HTTP paths into your Django project's urlpatterns in urls.py to handle ReactPy requests.
```python
from django.urls import path, include
urlpatterns = [
# ... other urls
path("_reactpy/", include("reactpy_django.urls")),
]
```
--------------------------------
### Django URL Patterns Configuration
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/router.md
Example of configuring Django's URL patterns to use the ReactPy router view. It's recommended to use a wildcard pattern to allow ReactPy to handle client-side routing. This ensures Django serves the initial page and ReactPy manages subsequent URL changes.
```python
from django.urls import re_path
from .views import my_reactpy_router_view
urlpatterns = [
re_path(r"^.*$", my_reactpy_router_view)
]
```
--------------------------------
### Example of Avoiding Local Link for Django Static CSS
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
This snippet illustrates an approach to avoid using `html.link` directly for local static files in Django, which can lead to incorrect load ordering. It's presented as an example of what not to do when `django_css` is available.
```python
from reactpy import html
# Avoid this for local static files, use django_css instead
def avoid_local_link_css():
return html.link({"rel": "stylesheet", "href": "/static/path/to/your/style.css"})
```
--------------------------------
### Implementing a Custom Postprocessor for use_query
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/hooks.md
Provides an example of creating and using a custom postprocessor function with the use_query hook. The custom postprocessor modifies the query data before it's returned.
```python
from reactpy import use_state
from reactpy_django.hooks import use_query
def custom_postprocessor(data, **kwargs):
# Custom data processing logic here
return modified_data
def custom_query_with_postprocessor():
todos, loading, error = use_query(Todo.objects.all, postprocessor=custom_postprocessor)
if loading:
return "Loading..."
if error:
return f"Error: {error}"
return html_component(todos=todos)
```
--------------------------------
### Example of Avoiding Local Script for Django Static JS
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
This snippet shows an approach to avoid directly using `html.script` for local static JavaScript files in Django, which can lead to unpredictable load times. It serves as an example of what to avoid when `django_js` is the preferred solution.
```python
from reactpy import html
# Avoid this for local static files, use django_js instead
def avoid_local_script_js():
return html.script({"src": "/static/path/to/your/script.js"})
```
--------------------------------
### Example of Incorrect Component Path Usage
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
This example highlights a common mistake when using the `component` template tag: passing a Django template/context variable for the component path. The ReactPy component finder requires a string literal path.
```django
{% component my_variable recipient="World" %}
{% component "example_project.my_app.components.hello_world" recipient="World" %}
```
--------------------------------
### Include PyScript HTML Template
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
This Jinja template tag includes the necessary HTML for PyScript components. It assumes a default setup with standard libraries, PyScript, Pyodide, and ReactPy core.
```jinja
{% include "../../examples/html/pyscript_component.html" %}
```
--------------------------------
### ReactPy-Django: Configure Database Router
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/settings.md
Example of configuring Django's DATABASE_ROUTERS to include ReactPy's database router. This is mandatory when REACTPY_DATABASE is configured to use a specific database for ReactPy's multiprocessing-safe database-backed hooks.
```python
DATABASE_ROUTERS = ["reactpy_django.database.Router", ...]
```
--------------------------------
### Python Example for Extra JS Object
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
A Python view function that prepares data, including an `extra_js` configuration for PyScript, to be passed to an HTML template. This demonstrates how to dynamically set JavaScript module dependencies from the backend.
```python
{% include "../../examples/python/pyscript_setup_extra_js_object.py" %}
```
--------------------------------
### Django URL Configuration for ReactPy View (Python)
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/learn/your-first-component.md
This Python code configures the URL routing for a Django project. It maps a specific URL path to the previously defined Django view function. This setup is essential for making the ReactPy component accessible via a web browser within the Django application.
```python
from django.urls import path
from . import views
urlpatterns = [
path('example/', views.my_view, name='example_view'),
]
```
--------------------------------
### Load JavaScript Modules in PyScript Setup (String)
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
Illustrates loading external JavaScript modules into PyScript by providing the `extra_js` parameter as a JSON string in a Jinja template. This method is an alternative to using a Python dictionary.
```jinja
{% include "../../examples/html/pyscript_setup_extra_js_string.html" %}
```
--------------------------------
### Specifying a Custom Root Component Name (HTML, Python)
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
Illustrates how to use the `root` keyword in PyScript to specify a different name for your root ReactPy component. Includes Jinja and Python examples.
```jinja
{% include "../../examples/html/pyscript_root.html" %}
```
```python
{% include "../../examples/python/pyscript_root.py" %}
```
--------------------------------
### Load JavaScript Modules in PyScript Setup (Object)
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
Shows how to load additional JavaScript modules into the PyScript environment using the `extra_js` parameter as a Python dictionary within a Jinja template. This allows for integrating external JavaScript functionality.
```jinja
{% include "../../examples/html/pyscript_setup_extra_js_object.html" %}
```
--------------------------------
### Configure PyScript for Local JavaScript Module Import
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
This Jinja template demonstrates the necessary setup for PyScript to import local JavaScript modules. It shows how to make modules available for use within Python components.
```jinja
{% include "../../examples/html/pyscript_local_import.html" %}
```
--------------------------------
### ReactPy-Django: Define Sync Postprocessor Function
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/settings.md
Example of a synchronous postprocessor function used by the use_query hook. This function modifies query data before it's returned. It can be any Python function, async or sync. If set to None, the default postprocessor is disabled.
```python
def postprocessor(data):
del data["foo"]
return data
```
--------------------------------
### Loading External CSS with HTML Link
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
This example demonstrates how to load external CSS stylesheets using ReactPy's `html.link` component. This is the recommended method for non-local CSS resources, as `django_css` is intended only for local static files.
```python
from reactpy import html
def external_css_link():
return html.link({"rel": "stylesheet", "href": "https://example.com/external/style.css"})
```
--------------------------------
### Defer JavaScript Loading with Django JS Component
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
This component enables deferring the loading of JavaScript until a ReactPy component starts rendering, using files stored in Django's static directory. It requires a `static_path` string and accepts an optional `key` for component identification.
```python
from reactpy import html
from reactpy.core.component import Component
def django_js(static_path: str, key: str | None = None) -> Component:
"""
Allows you to defer loading JavaScript until a component begins rendering.
This JavaScript must be stored within [Django's static files](https://docs.djangoproject.com/en/stable/howto/static-files/).
Args:
static_path: The path to the static file. This path is identical to what you would use on Django's {% static %} template tag.
key: A key to uniquely identify this component which is unique amongst a component's immediate siblings.
Returns:
A ReactPy component.
"""
return html.script({"src": f"/static/{static_path}"}, key=key)
```
--------------------------------
### Loading External JavaScript with HTML Script
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
This example demonstrates loading external JavaScript files using ReactPy's `html.script` component. It is the recommended method for non-local JavaScript resources, as `django_js` is specifically designed for local Django static files.
```python
from reactpy import html
def external_js_script():
return html.script({"src": "https://example.com/external/script.js"})
```
--------------------------------
### PyScript Component with Multiple Files in ReactPy
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
Illustrates how to manage a PyScript component that spans multiple files within a ReactPy application. This includes Python code for the root and child components, demonstrating modularity. The example shows how to import and use different Python files for a single PyScript component.
```python
from reactpy import component, html
from reactpy_django.pyapp import pyapp_tag
@component
def root():
return html.div(
pyapp_tag(file_paths=["../static/child.js"])
)
```
```python
from reactpy import component
@component
def root():
return "Hello from PyScript"
```
```python
from reactpy import component
@component
def child():
return "Hello from PyScript Child"
```
--------------------------------
### Python View for Template Tag Example
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
A Python view function associated with a Django template that utilizes ReactPy components. This snippet provides context for how the template tag might be used in conjunction with Django's view logic.
```python
from django.shortcuts import render
def my_view(request):
return render(request, "my_template.html")
```
--------------------------------
### Django ASGI Configuration with ReactPy WebSockets
Source: https://context7.com/reactive-python/reactpy-django/llms.txt
Configure your Django ASGI application to include ReactPy WebSocket support for real-time communication. This is essential for features like live chat or notifications.
```python
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example_project.settings")
django_asgi_app = get_asgi_application()
from channels.routing import ProtocolTypeRouter, URLRouter
from reactpy_django import REACTPY_WEBSOCKET_ROUTE
application = ProtocolTypeRouter({
"http": django_asgi_app,
"websocket": URLRouter([REACTPY_WEBSOCKET_ROUTE]),
})
```
--------------------------------
### Initial HTML Loading State for PyScript Component
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
Shows how to specify an initial HTML content to be displayed while a PyScript component is loading. The `initial` keyword argument can accept raw HTML strings, `reactpy.html` snippets, or non-interactive components. This provides a better user experience by showing something immediately.
```python
from reactpy import component, html
from reactpy_django.pyapp import pyapp_tag
@component
def parent():
return html.div(
pyapp_tag(
file_paths=["../static/child.js"],
initial=html.p("Loading PyScript component...")
)
)
```
```python
from reactpy import component, html
@component
def parent():
return html.div(
pyapp_tag(
file_paths=["../static/child.js"],
initial="
Loading PyScript...
"
)
)
```
--------------------------------
### use_query Hook Documentation
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/hooks.md
Documentation for the use_query hook, which executes functions in the background and returns results.
```APIDOC
## use_query Hook
### Description
Execute functions in the background and return the result, typically to read data from the Django ORM. The default postprocessor expects your query function to return a Django Model or QuerySet. This can be changed or disabled to execute other types of queries. Query functions can be sync or async.
### Method
N/A (This is a hook, not a direct API endpoint)
### Endpoint
N/A
### Parameters
#### Query Parameters
- **query** (Callable[FuncParams, Awaitable[Inferred]] | Callable[FuncParams, Inferred]) - Required - A function that executes a query and returns some data.
- **kwargs** (dict[str, Any] | None) - Optional - Keyword arguments to passed into the `query` function. Defaults to None.
- **thread_sensitive** (bool) - Optional - Whether to run your query function in thread sensitive mode. This setting only applies to sync functions, and is turned on by default due to Django ORM limitations. Defaults to True.
- **postprocessor** (AsyncPostprocessor | SyncPostprocessor | None) - Optional - A callable that processes the query `data` before it is returned. The first argument of postprocessor function must be the query `data`. All proceeding arguments are optional `postprocessor_kwargs`. This postprocessor function must return the modified `data`. Defaults to None.
- **postprocessor_kwargs** (dict[str, Any] | None) - Optional - Keyworded arguments passed into the `postprocessor` function. Defaults to None.
### Request Example
N/A (This is a hook, not a direct API endpoint)
### Response
#### Success Response (200)
- **Query** (Query[Inferred]) - An object containing `loading`/`error` states, your `data` (if the query has successfully executed), and a `refetch` callable that can be used to re-run the query.
#### Response Example
```json
{
"loading": false,
"error": null,
"data": "",
"refetch": ""
}
```
### Error Handling
Errors during query execution will be available in the `error` state of the returned Query object.
```
--------------------------------
### Set Up Local PyScript Interpreter
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
This Jinja template code configures PyScript to use a local Pyodide interpreter. It assumes the Pyodide bundle has been downloaded and placed in the project's static files, and specifies the path to use.
```jinja
{% include "../../examples/html/pyscript_setup_local_interpreter.html" %}
```
--------------------------------
### Django Form Class Example
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
This snippet demonstrates how to include a Django form class within a ReactPy application. It assumes the form class is defined in a separate Python file and is being included via a template tag.
```python
from django import forms
class ExampleForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
```
--------------------------------
### ReactPy Query with Refetch on Mutation
Source: https://context7.com/reactive-python/reactpy-django/llms.txt
Demonstrates coordinating database queries and mutations to automatically refresh data after a mutation occurs. Uses `use_query` and `use_mutation` with the `refetch` option.
```python
from reactpy import component, html
from example.models import TodoItem
from reactpy_django.hooks import use_query, use_mutation
from channels.db import database_sync_to_async
async def get_items():
return await database_sync_to_async(TodoItem.objects.all)()
async def add_item(text: str):
await TodoItem(text=text).asave()
@component
def todo_app():
item_query = use_query(get_items)
item_mutation = use_mutation(add_item, refetch=get_items)
def submit_event(event):
if event["key"] == "Enter":
item_mutation(text=event["target"]["value"])
if item_query.loading:
items_display = html.h2("Loading...")
elif item_query.error:
items_display = html.h2("Error loading items!")
else:
items_display = html.ul([html.li(item.text, key=item.pk) for item in item_query.data])
return html.div(
html.input({"type": "text", "onKeyDown": submit_event}),
items_display,
)
```
--------------------------------
### Customize Iframe Behavior with Extra Props (Python)
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
This example shows how to customize the behavior of the `iframe` element generated by `view_to_iframe`. It utilizes the `extra_props` argument to add custom attributes, such as a `title`, directly to the `iframe` tag.
```python
from typing import Any, Callable, Mapping
from django.http import HttpRequest, HttpResponse
from django.urls import path
from reactpy import html, run, web
def hello_world_fbv(request: HttpRequest) -> HttpResponse:
return HttpResponse("Hello World!")
def vti_extra_props(view: Callable | type, extra_props: Mapping[str, Any] | None = None) -> Callable:
"""Convert a Django view into a ReactPy component which renders as an iframe.
Compatible with sync or async Function Based Views and Class Based Views.
Args:
view: The view function or class to convert.
extra_props: Additional properties to add to the iframe element.
Returns:
A function that takes *args, key, **kwargs and returns a ReactPy component.
"""
def constructor(*args, key=None, **kwargs) -> html.iframe:
props = {"src": "/my-view/"} # TODO: implement url generation
if extra_props:
props.update(extra_props)
return html.iframe(props, key=key)
return constructor
# Example usage:
# Add a 'title' attribute to the iframe element.
my_component_extra_props = vti_extra_props(hello_world_fbv, extra_props={'title': 'My Custom Iframe Title'})
urlpatterns = [
path("/my-view/", hello_world_fbv),
path("/", web.create_client_app(my_component_extra_props)),
]
```
--------------------------------
### ReactPy Database Query Hook - use_query
Source: https://context7.com/reactive-python/reactpy-django/llms.txt
Fetches data from the database reactively using the `use_query` hook. It manages loading, error, and data states, and provides a refetch capability. Requires Django Channels for async database operations.
```python
from channels.db import database_sync_to_async
from reactpy import component, html
from example.models import TodoItem
from reactpy_django.hooks import use_query
async def get_items():
return await database_sync_to_async(TodoItem.objects.all)()
@component
def todo_list():
item_query = use_query(get_items)
if item_query.loading:
rendered_items = html.h2("Loading...")
elif item_query.error or not item_query.data:
rendered_items = html.h2("Error when loading!")
else:
rendered_items = html.ul([html.li(item.text, key=item.pk) for item in item_query.data])
return html.div("Rendered items: ", rendered_items)
```
--------------------------------
### Define a ReactPy Component in Django
Source: https://github.com/reactive-python/reactpy-django/blob/main/README.md
This Python code defines a simple ReactPy component named `hello_world` which takes a recipient string as input and renders an H1 HTML tag with a greeting. This component can be used within a Django application integrated with ReactPy.
```python
from reactpy import component, html
@component
def hello_world(recipient: str):
return html.h1(f"Hello {recipient}!")
```
--------------------------------
### Organizing ReactPy Components Across Multiple Files (HTML, Python)
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
Demonstrates how to split ReactPy components into multiple files for better organization, while maintaining type hints and avoiding local imports. Includes Jinja, Python.
```jinja
{% include "../../examples/html/pyscript_multiple_files.html" %}
```
```python
{% include "../../examples/python/pyscript_multiple_files_root.py" %}
```
```python
{% include "../../examples/python/pyscript_multiple_files_child.py" %}
```
--------------------------------
### Client-Side Python with PyScript in Django Templates
Source: https://context7.com/reactive-python/reactpy-django/llms.txt
Run Python components directly in the browser using PyScript for client-side interactivity within Django templates. This allows for a full Python stack, including front-end logic.
```jinja
{% load reactpy %}
ReactPy
{% pyscript_setup %}
{% component "example_project.my_app.components.server_side_component.py" %}
```
--------------------------------
### Define ReactPy Component in Python
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/learn/your-first-component.md
This Python code defines a simple ReactPy component named `hello_world` using the `@component` decorator. This decorator is necessary for components that will be referenced in Django templates or use hooks. The component accepts a `recipient` argument and renders a greeting.
```python
from reactpy import component
@component
def hello_world(recipient: str = "World"):
return f"Hello, {recipient}!"
```
--------------------------------
### ReactPy SPA Routing with Django URL Patterns
Source: https://context7.com/reactive-python/reactpy-django/llms.txt
Implement Single Page Applications (SPAs) using Django-style URL routing patterns with typed path converters. This enables flexible URL matching and parameter extraction for your ReactPy components.
```python
from reactpy import component, html
from reactpy_router import route
from reactpy_django.router import django_router
@component
def my_component():
return django_router(
route("/router/", html.div("Example 1")),
route("/router/any//", html.div("Example 2")),
route("/router/integer//", html.div("Example 3")),
route("/router/path//", html.div("Example 4")),
route("/router/slug//", html.div("Example 5")),
route("/router/string//", html.div("Example 6")),
route("/router/uuid//", html.div("Example 7")),
route("/router/two_values///", html.div("Example 8")),
route("/router/", html.div("Fallback")),
)
```
--------------------------------
### Create UI Components with Python
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/overrides/home.html
Demonstrates how to build user interfaces using ReactPy components written in pure Python. This includes conditional rendering with 'if' statements and list rendering using list comprehensions. The code is intended to be part of a larger ReactPy application.
```python
from reactpy import html
def thumbnail(video_id):
return html.div(
{
"class": "thumbnail",
"on_click": lambda: print(f"Clicked on {video_id}")
},
html.img({"src": f"/images/{video_id}.png"})
)
def like_button(video_id):
return html.button("Like")
def video(video_id):
return html.div(
thumbnail(video_id),
like_button(video_id)
)
app = html.div([
video("abc"),
video("def")
])
```
--------------------------------
### Configure Django settings.py for RedisChannelLayer
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/hooks.md
This Python code snippet demonstrates how to configure Django's settings.py file to use Redis as the channel layer backend. It specifies the backend class and connection configuration for the Redis server.
```python
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("127.0.0.1", 6379)],
},
},
}
```
--------------------------------
### Pass Args and Kwargs to Converted View (Python)
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
This example demonstrates how to pass positional and keyword arguments to a Django view that has been converted into a ReactPy iframe component using `view_to_iframe`. These arguments are encoded into the iframe's URL, so they must be serializable.
```python
from typing import Any, Callable, Mapping
from django.http import HttpRequest, HttpResponse
from django.urls import path
from reactpy import html, run, web
def hello_world_fbv(request: HttpRequest, greeting: str, name: str) -> HttpResponse:
return HttpResponse(f"{greeting}, {name}!")
def vti_args(view: Callable | type, extra_props: Mapping[str, Any] | None = None) -> Callable:
"""Convert a Django view into a ReactPy component which renders as an iframe.
Compatible with sync or async Function Based Views and Class Based Views.
Args:
view: The view function or class to convert.
extra_props: Additional properties to add to the iframe element.
Returns:
A function that takes *args, key, **kwargs and returns a ReactPy component.
"""
def constructor(*args, key=None, **kwargs) -> html.iframe:
# The *args and **kwargs are passed directly to the view.
# For view_to_iframe, they are encoded into the URL.
# TODO: Implement URL generation that includes args and kwargs.
props = {"src": "/my-view/"}
if extra_props:
props.update(extra_props)
return html.iframe(props, key=key)
return constructor
# Example usage:
# Pass positional and keyword arguments to the view.
my_component_args = vti_args(hello_world_fbv, extra_props={'title': 'Greeting View'})
urlpatterns = [
# Ensure the URL pattern matches how args/kwargs will be generated.
path("/my-view/", hello_world_fbv),
path("/", web.create_client_app(my_component_args)),
]
```
--------------------------------
### Displaying Content While PyScript Component Loads (HTML, Python)
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/template-tag.md
Shows how to configure the `initial` keyword in PyScript to display HTML content or a ReactPy component while the main component is loading. Supports Jinja and Python.
```jinja
{% include "../../examples/html/pyscript_initial_string.html" %}
```
```jinja
{% include "../../examples/html/pyscript_initial_object.html" %}
```
```python
{% include "../../examples/python/pyscript_initial_object.py" %}
```
--------------------------------
### Convert Class-Based Django View to Iframe Component (Python)
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
This snippet illustrates how to use `view_to_iframe` with Django Class Based Views. It shows the setup for converting a CBV, including the optional but recommended use of `.as_view()`, and integrating it into a ReactPy application.
```python
from typing import Any, Callable, Mapping
from django.http import HttpRequest, HttpResponse
from django.views import View
from django.urls import path
from reactpy import html, run, web
class HelloWorldCBV(View):
def get(self, request: HttpRequest) -> HttpResponse:
return HttpResponse("Hello World!")
def vti_cbv(view: Callable | type, extra_props: Mapping[str, Any] | None = None) -> Callable:
"""Convert a Django view into a ReactPy component which renders as an iframe.
Compatible with sync or async Function Based Views and Class Based Views.
Args:
view: The view function or class to convert.
extra_props: Additional properties to add to the iframe element.
Returns:
A function that takes *args, key, **kwargs and returns a ReactPy component.
"""
def constructor(*args, key=None, **kwargs) -> html.iframe:
# If the view is a class, call its as_view() method
if isinstance(view, type) and issubclass(view, View):
view_callable = view.as_view()
else:
view_callable = view
props = {"src": "/my-view/"} # TODO: implement url generation
if extra_props:
props.update(extra_props)
return html.iframe(props, key=key)
return constructor
my_component_cbv = vti_cbv(HelloWorldCBV)
urlpatterns = [
path("/my-view/", HelloWorldCBV.as_view()),
path("/", web.create_client_app(my_component_cbv)),
]
```
--------------------------------
### ReactPy Static File Loading with Django
Source: https://context7.com/reactive-python/reactpy-django/llms.txt
Dynamically load Django static files, such as CSS and JavaScript, within ReactPy components. This ensures that your component's styling and client-side scripts are correctly loaded.
```python
from reactpy import component, html
from reactpy_django.components import django_css, django_js
@component
def my_component():
return html.div(
django_css("css/styles.css"),
django_js("js/script.js"),
html.h1("Styled content"),
)
```
--------------------------------
### Load Simple PyScript Counter Component
Source: https://github.com/reactive-python/reactpy-django/blob/main/tests/test_app/templates/pyscript.html
Loads a basic ReactPy PyScript component, in this case, a counter. This demonstrates the straightforward loading of self-contained components.
```django
{% pyscript_component "./test_app/pyscript/components/counter.py" %}
```
--------------------------------
### Use Channel Layer API
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/hooks.md
Details about the `use_channel_layer` hook, its parameters, and return values for interacting with Django Channels.
```APIDOC
## Use Channel Layer Hook
### Description
Subscribes to a Django Channels Layer to communicate messages between different parts of your application. This is useful for features like chat systems, data synchronization, or signaling re-renders from outside ReactPy components.
### Method
Hook (Client-side Javascript equivalent, server-side Python execution)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **channel** (str | None) - The name of the channel this hook will send/receive messages on. If `group` is defined and `channel` is `None`, ReactPy will automatically generate a unique channel name. Defaults to `None`.
- **group** (str | None) - If configured, the `channel` is added to a `group` and any messages sent by `AsyncMessageSender` are broadcasted to all channels within the `group`. Defaults to `None`.
- **receiver** (AsyncMessageReceiver | None) - An async function that receives a `message: dict` from a channel. Defaults to `None`.
- **layer** (str) - The Django Channels layer to use. This layer must be defined in `settings.py:CHANNEL_LAYERS`. Defaults to `'default'`.
### Returns
- **AsyncMessageSender** - An async callable that can send messages to the channel(s). This callable accepts a single argument, `message: dict`, which is the data sent to the channel or group of channels.
### Request Example
```python
from reactpy import html, use_state
from reactpy_django.channels import use_channel_layer
async def message_handler(message):
print(f"Received message: {message}")
def App():
message_sender = use_channel_layer(channel="my-channel", receiver=message_handler)
async def send_message():
await message_sender({"text": "Hello from ReactPy!"})
return html.div([
html.button({"on_click": send_message}, "Send Message")
])
```
### Response
#### Success Response (200)
This hook does not directly return a response in the traditional HTTP sense. It provides an `AsyncMessageSender` callable.
#### Response Example
```python
# Example of using the returned AsyncMessageSender
# async def send_message_to_channel(sender):
# await sender({'type': 'chat', 'text': 'New message!'})
```
### Error Handling
- **Django Configuration**: Ensure `CHANNEL_LAYERS` is configured in `settings.py`.
- **Channel Layer Backend**: The specified layer backend (e.g., `channels_redis.core.RedisChannelLayer`) must be installed and running.
```
--------------------------------
### ReactPy Component with Custom Transforms (Python)
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
Shows how to customize the VDOM output of a converted Django view using the `transforms` argument in `view_to_component`. This Python example defines a transform function to modify VDOM nodes, such as adding CSS classes to `
` elements.
```python
from django.http import HttpRequest
from reactpy import VdomDict
from reactpy_django.utils import view_to_component
def hello_world_fbv_with_id(request: HttpRequest) -> str:
return "
Hello World
"
def add_class_to_h1(vdom: VdomDict) -> VdomDict:
if vdom.get("tagName") == "h1":
vdom.setdefault("attributes", {}).setdefault("classes", []).append("my-custom-class")
return vdom
# Convert Function Based View to Component with a transform
HelloComponentTransforms = view_to_component(hello_world_fbv_with_id, transforms=(add_class_to_h1,))
```
--------------------------------
### Embed PyScript Component with Parent/Root in ReactPy
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
Demonstrates how to embed a PyScript component, acting as a parent, within a ReactPy application. It includes Python code for the parent and root components, and an HTML template for integration. This setup allows for client-side PyScript execution managed by ReactPy.
```python
from reactpy import component, html
from reactpy_django.pyapp import pyapp_tag
@component
def parent():
return html.div(
pyapp_tag(file_paths=["../static/child.js"])
)
```
```python
from reactpy import component, html
@component
def root():
return html.div("Hello from PyScript")
```
```jinja
{% load pyapp %}
PyScript SSR Parent
{% pyscript_setup %}
{% pyapp parent() %}
```
--------------------------------
### ReactPy Real-time Messaging with Django Channels
Source: https://context7.com/reactive-python/reactpy-django/llms.txt
Enable real-time cross-component communication using Django Channels for publish-subscribe messaging. This allows components to send and receive messages asynchronously, facilitating live updates.
```python
from reactpy import component, hooks, html
from reactpy_django.hooks import use_channel_layer
@component
def my_component():
async def receive_message(message):
set_message_data(message["text"])
async def send_message(event):
if event["key"] == "Enter":
await sender({"text": event["target"]["value"]})
message_data, set_message_data = hooks.use_state("")
sender = use_channel_layer(group="my-group-name", receiver=receive_message)
return html.div(
f"Received: {message_data}",
html.br(),
"Send: ",
html.input({"type": "text", "onKeyDown": send_message}),
)
```
--------------------------------
### ReactPy Django Router Component Usage
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/router.md
Illustrates the usage of the Django Router component within a ReactPy application. This component takes routes as arguments, where each route defines a path, an element to render, and potential child routes. It returns the matched component or None.
```python
from reactpy import html, use_state
from reactpy_django import django_router, Route
def hello_world():
return html.h1("Hello World!")
def page_one():
return html.h1("Page One")
def page_two():
return html.h1("Page Two")
def app():
return django_router(
Route("/", hello_world),
Route("/page-one", page_one),
Route("/page-two", page_two)
)
```
--------------------------------
### Django URL Configuration for ReactPy HTTP Endpoints
Source: https://context7.com/reactive-python/reactpy-django/llms.txt
Register ReactPy HTTP endpoints within your Django URL configuration. This allows Django to serve your ReactPy components via standard HTTP requests.
```python
from django.urls import include, path
urlpatterns = [
path("reactpy/", include("reactpy_django.http.urls")),
]
```
--------------------------------
### ReactPy Component Registration in Django Apps
Source: https://context7.com/reactive-python/reactpy-django/llms.txt
Register ReactPy components during Django app initialization for proper resolution by template tags. This ensures that your components are discoverable and can be rendered within templates.
```python
from django.apps import AppConfig
from reactpy_django.utils import register_component
class ExampleAppConfig(AppConfig):
name = "example"
def ready(self):
register_component("example_project.my_app.components.hello_world")
```
--------------------------------
### ReactPy Database Mutation Hook - use_mutation
Source: https://context7.com/reactive-python/reactpy-django/llms.txt
Handles database mutations reactively with `use_mutation`. It automatically refetches queries upon successful mutation and manages loading/error states. Asynchronous mutations are supported.
```python
from reactpy import component, html
from example.models import TodoItem
from reactpy_django.hooks import use_mutation
async def add_item(text: str):
await TodoItem(text=text).asave()
@component
def todo_list():
item_mutation = use_mutation(add_item)
def submit_event(event):
if event["key"] == "Enter":
item_mutation(text=event["target"]["value"])
if item_mutation.loading:
mutation_status = html.h2("Adding...")
elif item_mutation.error:
mutation_status = html.h2("Error when adding!")
else:
mutation_status = html.h2("Mutation done.")
return html.div(
html.label("Add an item:"),
html.input({"type": "text", "onKeyDown": submit_event}),
mutation_status,
)
```
--------------------------------
### Specify Root Component Name for PyScript in ReactPy
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/components.md
Demonstrates how to specify a custom name for the root PyScript component using the `root` keyword argument. This is useful when the main PyScript function is not named 'root'. The example includes Python code for the component and a main script to demonstrate the custom root name.
```python
from reactpy import component, html
from reactpy_django.pyapp import pyapp_tag
@component
def parent():
return html.div(
pyapp_tag(
file_paths=["../static/main.js"],
root="my_custom_root"
)
)
```
```python
from reactpy import component
@component
def my_custom_root():
return "Hello from a custom root component!"
```
--------------------------------
### Jinja2 Template Rendering Components
Source: https://github.com/reactive-python/reactpy-django/blob/main/tests/test_app/templates/time_to_load.html
This Jinja2 template snippet demonstrates how to render multiple ReactPy components dynamically within a loop. It utilizes the 'component' tag provided by the reactpy template tags. The number of components rendered is determined by the 'count' variable in the Django context.
```jinja2
{% load static %} {% load reactpy %} ReactPy
ReactPy Time To Load Test Page
==============================
**
Total Active Components:
Time To Load:
**
* * *
{% for x in count %} **Worker {{x}}** {% component "test\_app.performance.components.time\_to\_load" %}
* * *
{% endfor %}
```
--------------------------------
### Get Root Component ID with use_root_id (Python)
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/hooks.md
The `use_root_id` hook returns the unique identifier of the root component instance from the current WebSocket or HTTP connection. This ID is a persistent UUID within the connection, resetting only on page refresh. It's particularly useful when combined with `use_channel_layer` to direct messages to specific component instances.
```python
from reactpy import html, use_state, use_root_id
def hello_world():
root_id = use_root_id()
return html.div(f"Root ID: {root_id}")
```
--------------------------------
### Embed ReactPy Component in Django Template (Jinja)
Source: https://github.com/reactive-python/reactpy-django/blob/main/README.md
This snippet demonstrates how to use the 'component' template tag in a Django HTML file to render a ReactPy component. It shows how to load the reactpy tags and specify the component path along with its arguments.
```jinja
{% load reactpy %}
{% component "example_project.my_app.components.hello_world" recipient="World" %}
```
--------------------------------
### Passing Postprocessor Keyword Arguments in use_query
Source: https://github.com/reactive-python/reactpy-django/blob/main/docs/src/reference/hooks.md
Shows how to pass additional keyword arguments to a custom postprocessor function via the `postprocessor_kwargs` parameter in the use_query hook.
```python
from reactpy import use_state
from reactpy_django.hooks import use_query
def custom_postprocessor_with_args(data, format=None):
if format == 'summary':
return [f"{item.title} - {'Completed' if item.completed else 'Pending'}" for item in data]
return data
def custom_query_with_postprocessor_kwargs():
todos, loading, error = use_query(
Todo.objects.all,
postprocessor=custom_postprocessor_with_args,
postprocessor_kwargs={"format": "summary"}
)
if loading:
return "Loading..."
if error:
return f"Error: {error}"
return html_component(todos=todos)
```