### Run ReactPy Sample Application
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/index.rst
Executes a sample ReactPy application using the Python interpreter. This is a quick way to verify your installation and see a basic ReactPy app in action. It requires ReactPy to be installed with a compatible server, such as Starlette.
```python
import reactpy
reactpy.run(reactpy.sample.SampleApp)
```
--------------------------------
### Python Package Setup with Custom Build Commands (setup.py)
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/escape-hatches/distributing-javascript.rst
Configures the Python package metadata and customizes Setuptools build commands to include a JavaScript build step. It defines package name, version, dependencies, and integrates `npm install` and `npm run build` into the `sdist`, `build`, and `develop` commands.
```python
import subprocess
from pathlib import Path
from setuptools import setup, find_packages
from distutils.command.build import build
from distutils.command.sdist import sdist
from setuptools.command.develop import develop
PACKAGE_SPEC = {} # gets passed to setup() at the end
# -----------------------------------------------------------------------------
# General Package Info
# -----------------------------------------------------------------------------
PACKAGE_NAME = "your_python_package"
PACKAGE_SPEC.update(
name=PACKAGE_NAME,
version="0.0.1",
packages=find_packages(exclude=["tests*"]),
classifiers=["Framework :: ReactPy", ...],
keywords=["ReactPy", "components", ...],
# install ReactPy with this package
install_requires=["reactpy"],
# required in order to include static files like bundle.js using MANIFEST.in
include_package_data=True,
# we need access to the file system, so cannot be run from a zip file
zip_safe=False,
)
# ----------------------------------------------------------------------------
# Build Javascript
# ----------------------------------------------------------------------------
# basic paths used to gather files
PROJECT_ROOT = Path(__file__).parent
PACKAGE_DIR = PROJECT_ROOT / PACKAGE_NAME
JS_DIR = PROJECT_ROOT / "js"
def build_javascript_first(cls):
class Command(cls):
def run(self):
for cmd_str in ["npm install", "npm run build"]:
subprocess.run(cmd_str.split(), cwd=str(JS_DIR), check=True)
super().run()
return Command
package["cmdclass"] = {
"sdist": build_javascript_first(sdist),
"build": build_javascript_first(build),
"develop": build_javascript_first(develop),
}
# -----------------------------------------------------------------------------
# Run It
# ----------------------------------------------------------------------------
if __name__ == "__main__":
setup(**package)
```
--------------------------------
### Install ReactPy with Starlette Backend
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/installing-reactpy.rst
Installs ReactPy along with the Starlette backend using pip. This is a common way to get started with ReactPy for web applications.
```bash
pip install "reactpy[starlette]"
```
--------------------------------
### Hello World Example in ReactPy
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/index.rst
A basic 'Hello World' example demonstrating how to create a simple ReactPy application. It imports necessary tools, defines an App component using the @component decorator, and runs a development web server.
```python
from reactpy import component, run
@component
def App():
return "
Hello world!
"
run(App)
```
--------------------------------
### Install ReactPy for Development
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/installing-reactpy.rst
Installs a development version of ReactPy by cloning the repository. This is for users who want to contribute to ReactPy's source code or modify it.
```bash
git clone https://github.com/reactive-python/reactpy.git
cd reactpy
pip install -e .[dev]
```
--------------------------------
### Install ReactPy with Multiple Native Backends
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/installing-reactpy.rst
Installs ReactPy with support for multiple native backends simultaneously. This allows flexibility in choosing or switching between different web server frameworks.
```bash
pip install "reactpy[fastapi,flask,sanic,starlette,tornado]"
```
--------------------------------
### Install Pure ReactPy (No Backend)
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/installing-reactpy.rst
Installs ReactPy without any backend implementation. This is useful for custom backend integrations or manual dependency pinning.
```bash
pip install reactpy
```
--------------------------------
### ReactPy Development Server Log Output
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/index.rst
Example log messages displayed when running a ReactPy development server. These logs indicate that a development server is active and provide the URL where the application can be accessed. It's crucial to note the warning about using this server in production.
```text
2022-03-27T11:58:59-0700 | WARNING | You are running a development server. Change this before deploying in production!
2022-03-27T11:58:59-0700 | INFO | Running with 'Starlette' at http://127.0.0.1:8000
```
--------------------------------
### Manage Development Environments - Hatch
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/about/contributor-guide.rst
Commands for managing Hatch's virtual environments and Python installations. Useful for cleaning up old environments or installing specific Python versions.
```bash
hatch build --clean
hatch env prune
hatch python install 3.12
```
--------------------------------
### Manage Documentation - Hatch
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/about/contributor-guide.rst
Commands for building and serving ReactPy's documentation using Hatch. Includes options for local preview, building, checking for errors, and using Docker for builds and serving.
```bash
hatch run docs:serve
hatch run docs:build
hatch run docs:check
hatch run docs:docker_serve
hatch run docs:docker_build
```
--------------------------------
### Handle Missing Server Implementation Error
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/index.rst
Example of a RuntimeError that may occur if no supported server implementation is found. This error typically indicates that ReactPy was installed without the necessary server integration package, such as `[starlette]`. Reinstalling with the correct integration is the solution.
```text
Found none of the following builtin server implementations...
```
--------------------------------
### Set Color 3 Times Example (Python)
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/adding-interactivity/index.rst
Demonstrates how multiple synchronous state updates within an event handler are batched and trigger a single re-render. This example shows setting a color state three times in quick succession.
```python
from typing import cast
from reactpy import html, run, use_state
def multiple_state_updates():
count, set_count = use_state(0)
def set_count_three_times():
set_count(count + 1)
set_count(count + 1)
set_count(count + 1)
return html.div(
html.p(f"Count: {count}"),
html.button({"on_click": set_count_three_times}, "Click Me")
)
run(multiple_state_updates)
```
--------------------------------
### Rendering Data with Keys in ReactPy
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/index.rst
This example demonstrates how to render lists of data in ReactPy, emphasizing the importance of using keys for efficient updates. It shows how to create a todo list interface from raw data.
```python
from reactpy import component, html, run
@component
def TodoList():
todos = [
{"id": 1, "text": "Learn ReactPy", "done": False},
{"id": 2, "text": "Build an app", "done": False},
{"id": 3, "text": "Have fun!", "done": True},
]
return html.ul([
html.li({"key": todo["id"]}, todo["text"])
for todo in todos
])
run(TodoList)
```
--------------------------------
### Mount ReactPy App with WebSocket
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/_static/embed-reactpy-view/index.html
This snippet demonstrates how to mount a ReactPy application using a WebSocket connection. It initializes `LayoutServerInfo` with server details and then mounts the application to a specified DOM element. Requires `@reactpy/client` library.
```javascript
import { mountWithLayoutServer, LayoutServerInfo, } from "https://esm.sh/@reactpy/client@0.38.0";
const serverInfo = new LayoutServerInfo({
host: document.location.hostname,
port: document.location.port,
path: "_reactpy",
query: queryParams.user.toString(),
secure: document.location.protocol == "https:",
});
mountLayoutWithWebSocket(
document.getElementById("reactpy-app"),
serverInfo
);
```
--------------------------------
### ReactPy Hello World Component in Python
Source: https://github.com/reactive-python/reactpy/blob/main/README.md
A simple 'Hello World' application using ReactPy. This example demonstrates how to define a basic component and run it. It requires the reactpy library.
```python
from reactpy import component, html, run
@component
def hello_world():
return html.h1("Hello, World!")
run(hello_world)
```
--------------------------------
### Install Flake8 Plugin for ReactPy Hooks
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/reference/hooks-api.rst
This command installs the flake8-reactpy-hooks plugin, which helps enforce the rules for calling hooks in ReactPy. It can be installed directly or with the 'lint' extra for ReactPy.
```bash
pip install flake8-reactpy-hooks
```
--------------------------------
### Clone ReactPy Repository - Bash
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/about/contributor-guide.rst
Clones the ReactPy repository from GitHub and navigates into the project directory. This is the first step for anyone intending to make code changes.
```bash
git clone https://github.com/reactive-python/reactpy.git
cd reactpy
```
--------------------------------
### Run ReactPy View with Python Server
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/running-reactpy.rst
This Python code sets up a basic web server using a Python framework to serve a ReactPy application. It defines the main application logic and how to render the ReactPy view. The `main.py` file is intended to be run to start the server.
```python
from pathlib import Path
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.staticfiles import StaticFiles
from reactpy import html, run
def homepage():
return html.h1("Hello, world!")
routes = [
Route("/", endpoint=homepage),
Route("/static/", StaticFiles(directory=Path(__file__).parent / "static")),
]
app = Starlette(routes=routes)
if __name__ == "__main__":
run(app, port=8000)
```
--------------------------------
### Javascript Component Usage Example - Javascript
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/escape-hatches/javascript-components.rst
Illustrates the basic usage pattern of a Javascript component's 'bind' function. It shows the sequence of operations for mounting, rendering, and unmounting the component within a web page.
```javascript
// once on mount
const binding = bind(node, context);
// on every render
let element = binding.create(type, props, children)
binding.render(element);
// once on unmountinding.unmount();
```
--------------------------------
### Enabling ReactPy Debug Mode in Windows Command Prompt
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/running-reactpy.rst
This example shows how to enable ReactPy's debug mode by setting the REACTPY_DEBUG environment variable to '1' in the Windows Command Prompt before running the Python application.
```text
set REACTPY_DEBUG=1
python my_reactpy_app.py
```
--------------------------------
### Mount Layout with WebSocket (JavaScript)
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/_static/embed-doc-ex.html
This snippet demonstrates how to mount a ReactPy layout using a WebSocket connection. It utilizes the `mountLayoutWithWebSocket` function from the `@reactpy/client` library. This function requires a DOM element to mount the application and a WebSocket URL for communication.
```javascript
import { mountLayoutWithWebSocket } from "https://esm.sh/@reactpy/client";
mountLayoutWithWebSocket( document.getElementById("reactpy-app"), "wss://reactpy.dev/_reactpy/stream?view_id=todo" );
```
--------------------------------
### Enabling ReactPy Debug Mode in PowerShell
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/running-reactpy.rst
This example shows how to enable ReactPy's debug mode by setting the REACTPY_DEBUG environment variable to '1' in PowerShell before running the Python application.
```powershell
$env:REACTPY_DEBUG = "1"
python my_reactpy_app.py
```
--------------------------------
### Set State Function Example (Python)
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/adding-interactivity/index.rst
Illustrates how to use an updater function with a state setter to apply incremental updates. This is useful when the next state depends on the previous state, and you need updates to be applied sequentially rather than batched.
```python
from typing import cast
from reactpy import html, run, use_state
def set_state_function():
count, set_count = use_state(0)
def increment_count():
set_count(lambda c: c + 1)
set_count(lambda c: c + 1)
set_count(lambda c: c + 1)
return html.div(
html.p(f"Count: {count}"),
html.button({"on_click": increment_count}, "Increment")
)
run(set_state_function)
```
--------------------------------
### Simple SVG Line Chart using htm - ReactPy Example
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/escape-hatches/javascript-components.rst
A basic example of a custom Javascript component for drawing an SVG line chart. It uses 'htm' to simulate JSX in plain Javascript, as direct JSX compilation is not supported in browser-runnable Javascript for this scenario.
```python
from reactpy import html, run
def app(req):
return html.div(f"""
""")
run(app)
```
--------------------------------
### Dictionary Update Example (Python)
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/adding-interactivity/index.rst
Shows the correct way to update a dictionary held in state by creating a new dictionary with the desired changes, rather than mutating the existing one. This ensures ReactPy detects the change and triggers a re-render.
```python
from typing import cast
from reactpy import html, run, use_state
def dict_update():
user, set_user = use_state({"name": "Alice", "age": 30})
def update_user_age():
# Incorrect way: Mutating the existing dictionary
# user["age"] = user["age"] + 1
# set_user(user)
# Correct way: Creating a new dictionary with the update
set_user({"name": user["name"], "age": user["age"] + 1})
return html.div(
html.p(f"Name: {user['name']}, Age: {user['age']}"),
html.button({"on_click": update_user_age}, "Increase Age")
)
run(dict_update)
```
--------------------------------
### Manage JavaScript Packages - Hatch
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/about/contributor-guide.rst
Commands to manage JavaScript packages within the ReactPy project using Hatch. Includes options for checking, fixing, testing, and building various JavaScript components.
```bash
hatch run javascript:check
hatch run javascript:fix
hatch run javascript:test
hatch run javascript:build
hatch run javascript:build_event_to_object
hatch run javascript:build_client
hatch run javascript:build_app
```
--------------------------------
### Conditional Rendering in ReactPy (Basic If)
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/creating-interfaces/your-first-components/index.rst
Shows a basic approach to conditional rendering in ReactPy using an if-else statement within the render function. This example renders a checkmark if a todo item is marked as 'done'.
```python
from reactpy import component, html
@component
def Item(name: str, done: bool):
if done:
return html.li(name, " ✔")
else:
return html.li(name)
@component
def TodoList():
return html.ul([
Item(name="Buy groceries", done=True),
Item(name="Walk the dog", done=False),
])
```
--------------------------------
### Enabling ReactPy Debug Mode in Unix Shell
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/running-reactpy.rst
This example shows how to enable ReactPy's debug mode by setting the REACTPY_DEBUG environment variable to '1' in a Unix-like shell (Linux, macOS, etc.) before running the Python application.
```bash
export REACTPY_DEBUG=1
python my_reactpy_app.py
```
--------------------------------
### Embed ReactPy Example in HTML
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/running-reactpy.rst
This HTML code snippet demonstrates how to embed a ReactPy component into a standard HTML page. It requires a JavaScript file to load and render the ReactPy application. The primary function is to serve as a container for the ReactPy view.
```html
ReactPy Example
```
--------------------------------
### Display Material UI Button (No Action) - ReactPy Example
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/escape-hatches/javascript-components.rst
Demonstrates how to display a Material UI Button using ReactPy. It leverages dynamically loaded Javascript via a CDN. No specific Python dependencies are mentioned other than ReactPy itself.
```python
from reactpy import html, run
from .material_ui_button import ui_button
def app(req):
return ui_button("A Button")
run(app)
```
--------------------------------
### Format and Lint Python Code - Hatch
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/about/contributor-guide.rst
Commands for managing Python code formatting and linting using Hatch. Includes options to check formatting without applying changes, run only linters, or run only formatters.
```bash
hatch fmt
hatch fmt --check
hatch fmt --linter
hatch fmt --formatter
```
--------------------------------
### Import Custom ReactJS Components from Local Files using ReactPy
Source: https://context7.com/reactive-python/reactpy/llms.txt
The `component_from_file` function in ReactPy allows loading and using custom JavaScript/React components defined in local files. This is useful for integrating pre-existing or custom UI elements. The example shows importing a `CustomButton` component from a `custom_components.js` file.
```python
from pathlib import Path
from reactpy import component, html
from reactpy.reactjs import component_from_file, import_reactjs
# custom_components.js:
# export function CustomButton({ label, onClick }) {
# return React.createElement('button', { onClick, className: 'custom-btn' }, label);
# Assuming custom_components.js is in the same directory or a known path
# You might need to adjust the path based on your project structure
# For example, if it's in a 'static/js' folder:
# CUSTOM_BUTTON_PATH = Path(__file__).parent / "static" / "js" / "custom_components.js"
# For demonstration, let's assume it's directly importable or available via a path
# In a real scenario, you'd configure how ReactPy finds these files.
# Example placeholder for component_from_file (actual implementation depends on file location)
# CustomButton = component_from_file(Path("path/to/your/custom_components.js"), "CustomButton")
# Placeholder component if the file isn't readily available for direct import in this context
# In a real app, this would be replaced by the actual imported component.
@component
def PlaceholderCustomButton(label, onClick):
# This is a conceptual representation. The actual component is loaded from JS.
print(f"Placeholder for CustomButton: {label}")
return html.button({"onClick": onClick, "className": "custom-btn"}, label)
@component
def AppWithCustomComponent():
def handle_click():
print("Custom button clicked!")
return html.div(
import_reactjs(framework="react", version="18"), # Necessary for external JS components
html.h1("Using Custom JS Component"),
# Replace PlaceholderCustomButton with the actual imported component
# CustomButton(label="Click Me", onClick=handle_click)
PlaceholderCustomButton(label="Click Me", onClick=handle_click)
)
```
--------------------------------
### Syncing Input and List State with Lifted State Up in ReactPy
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/managing-state/index.rst
This example demonstrates how to synchronize the state between an input field and a list of elements by lifting the state to their common parent component. The parent component manages the shared state and passes it down as props, allowing child components to react to changes automatically. This pattern is crucial for enabling components to vary together.
```python
from pyweb.react import hooks
from pyweb.html import div, input_, p, table, tbody, td, tr
@hooks.component
def Table(props):
items = props.get("items", [])
return table(
tbody([
tr([
td([item])
]) for item in items
])
)
@hooks.component
def SyncedInputs(props):
search_query, set_search_query = hooks.use_state("")
return div([
input_(
{ "type": "text", "placeholder": "Search for food...", "value": search_query, "on_change": lambda _, __, value: set_search_query(value) }
),
Table({"items": ["Apple", "Orange", "Banana"]})
])
```
--------------------------------
### Configuring ReactPy Backend with Options
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/running-reactpy.rst
This snippet illustrates how to pass backend-specific options to the `configure` function when setting up a ReactPy application. It shows the general pattern using `Options(...)` and references documentation for specific backend options.
```python
from reactpy.backend. import configure, Options
configure(app, MyComponent, Options(...))
```
--------------------------------
### Python Build System Configuration (pyproject.toml)
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/escape-hatches/distributing-javascript.rst
Specifies the build system requirements for the Python package. It declares that Setuptools should be used as the build backend and lists the necessary dependencies, including setuptools and wheel.
```toml
[build-system]
requires = ["setuptools>=40.8.0", "wheel"]
build-backend = "setuptools.build_meta"
```
--------------------------------
### Index HTML for ReactPy Application
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/running-reactpy.rst
This HTML file serves as the entry point for a ReactPy application. It includes the necessary script tags to load ReactPy and its dependencies, and a div with the ID 'app' where the ReactPy component will be mounted. This file works in conjunction with the Python backend to display the application.
```html
ReactPy App
```
--------------------------------
### Display Material UI Button with OnClick Handler - ReactPy Example
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/escape-hatches/javascript-components.rst
Shows how to add an onClick handler to a Material UI Button displayed with ReactPy. This builds upon the previous example by passing event handlers, similar to basic ReactPy event handling.
```python
from reactpy import html, run, event
from .material_ui_button import ui_button
def app(req):
return ui_button("A Button", on_click=event(lambda _, target: print(f"Button {target} clicked!")))
run(app)
```
--------------------------------
### Type Check Python Code - Hatch
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/about/contributor-guide.rst
Executes the Python type checker for the ReactPy project using Hatch. Ensures code adheres to type hints and static typing standards.
```bash
hatch run python:type_check
```
--------------------------------
### Basic Backend Configuration for ReactPy
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/running-reactpy.rst
This snippet demonstrates the fundamental structure for configuring a ReactPy application with a chosen backend. It includes importing necessary components, defining a simple ReactPy component, and then configuring the backend application with this component. This pattern is common across various supported backends.
```python
from my_chosen_backend import Application
from reactpy import component, html
from reactpy.backend.my_chosen_backend import configure
@component
def HelloWorld():
return html.h1("Hello, world!")
app = Application()
configure(app, HelloWorld)
```
--------------------------------
### Running ReactPy App with Uvicorn (FastAPI/Starlette)
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/running-reactpy.rst
This command demonstrates how to run a ReactPy application configured with FastAPI or Starlette using the Uvicorn ASGI server. It assumes the application instance is named 'app' and is defined in a file named 'main.py'.
```bash
uvicorn main:app
```
--------------------------------
### Running ReactPy App with Sanic Built-in Server
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/running-reactpy.rst
This command demonstrates how to run a ReactPy application configured with Sanic using its built-in server. It assumes the application instance is named 'app' and is defined in a file named 'main.py'.
```bash
sanic main.app
```
--------------------------------
### ReactPy Fragment for Grouping List Items
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/creating-interfaces/your-first-components/index.rst
Example of using `html._` (fragment) to group list items within a ``. This avoids adding unnecessary `div` elements and directly translates to the desired HTML structure.
```python
from reactpy import html
html.ul(
html._(
html.li("Group 1 Item 1"),
html.li("Group 1 Item 2"),
html.li("Group 1 Item 3"),
),
html._(
html.li("Group 2 Item 1"),
html.li("Group 2 Item 2"),
html.li("Group 2 Item 3"),
)
)
```
--------------------------------
### Running Flake8 Linter on ReactPy Components
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/reference/hooks-api.rst
This command demonstrates how to run the flake8 linter on your ReactPy component files to catch rule violations. The output shows example error messages for incorrect hook usage.
```bash
flake8 my_reactpy_components.py
```
--------------------------------
### Including JavaScript Bundle in Python Package (MANIFEST.in)
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/escape-hatches/distributing-javascript.rst
Instructs the Setuptools build process to include the generated JavaScript bundle file (`bundle.js`) in the source distribution (sdist). This ensures that the bundled JavaScript is packaged correctly with the Python library.
```text
include your_python_package/bundle.js
```
--------------------------------
### Build Standalone ASGI App with ReactPy
Source: https://context7.com/reactive-python/reactpy/llms.txt
The `ReactPy` class enables the creation of standalone ASGI applications, ideal for single-page applications. It allows defining the root component, HTML head elements, and custom API routes. The application can be run using ASGI servers like uvicorn.
```python
from reactpy import component, html
from reactpy.executors.asgi import ReactPy
@component
def App():
return html.div(
html.h1("My ReactPy App"),
html.p("This is a standalone ASGI application.")
)
# Create standalone app
app = ReactPy(
App,
html_head=html.head(
html.title("My App"),
html.meta({"charset": "utf-8"}),
html.link({"rel": "stylesheet", "href": "/static/style.css"})
),
html_lang="en"
)
# Add custom routes
@app.route("/api/hello", type="http")
async def hello_api(scope, receive, send):
from asgi_tools import ResponseJSON
response = ResponseJSON({"message": "Hello from API!"})
await response(scope, receive, send)
# Run with uvicorn:
# uvicorn myapp:app --reload
```
--------------------------------
### ReactPy: use_context and create_context for State Management
Source: https://context7.com/reactive-python/reactpy/llms.txt
Demonstrates how to use `create_context` to create context objects with default values and `use_context` to access these values within descendant components. This avoids prop drilling by providing a global state accessible throughout the component tree.
```python
from reactpy import component, html, use_context, create_context, use_state
# Create context with default value
ThemeContext = create_context("light")
UserContext = create_context(None)
@component
def ThemedButton():
theme = use_context(ThemeContext)
user = use_context(UserContext)
styles = {
"light": {"backgroundColor": "white", "color": "black"},
"dark": {"backgroundColor": "#333", "color": "white"}
}
return html.button(
{"style": styles[theme]},
f"Hello, {user['name'] if user else 'Guest'}!"
)
@component
def Toolbar():
return html.div(
{"className": "toolbar"},
ThemedButton()
)
@component
def App():
theme, set_theme = use_state("light")
user = {"name": "Alice", "role": "admin"}
def toggle_theme(event):
set_theme("dark" if theme == "light" else "light")
return ThemeContext(
UserContext(
html.div(
html.button({"onClick": toggle_theme}, f"Theme: {theme}"),
Toolbar()
),
value=user
),
value=theme
)
```
--------------------------------
### Async State Update and Print in Python
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/adding-interactivity/state-as-a-snapshot/index.rst
Demonstrates setting state, introducing a delay, and printing a value that reflects the state at the time of the initial render. This highlights how state remains static within a render context.
```python
set_number(0 + 5)
print("about to print...")
await asyncio.sleep(3)
print(0)
```
--------------------------------
### Run Python Tests - Hatch
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/about/contributor-guide.rst
Commands to execute Python tests within the ReactPy project using the Hatch build tool. Supports running all tests, tests for specific Python versions, or filtering by test name.
```bash
hatch test
hatch test --all
hatch test --python 3.9
hatch test -k test_use_connection
```
--------------------------------
### ReactPy: use_memo and use_callback for Performance Optimization
Source: https://context7.com/reactive-python/reactpy/llms.txt
Explains the use of `use_memo` for memoizing expensive computations and `use_callback` for memoizing callback functions. These hooks help prevent unnecessary re-renders by caching results and function instances, improving application performance.
```python
from reactpy import component, html, use_state, use_memo, use_callback
@component
def ExpensiveList(items: list, filter_text: str):
# Memoize expensive filtering operation
filtered_items = use_memo(
lambda: [item for item in items if filter_text.lower() in item.lower()],
dependencies=[items, filter_text]
)
# Memoize callback to prevent child re-renders
@use_callback(dependencies=[])
def handle_item_click(item_id):
print(f"Clicked item: {item_id}")
return html.ul([
html.li(
{"key": item, "onClick": lambda e, i=item: handle_item_click(i)},
item
)
for item in filtered_items
])
@component
def SearchableList():
items = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
filter_text, set_filter = use_state("")
return html.div(
html.input({
"placeholder": "Filter items...",
"value": filter_text,
"onChange": lambda e: set_filter(e["target"]["value"])
}),
ExpensiveList(items, filter_text)
)
```
--------------------------------
### Running ReactPy App with Gunicorn (Flask)
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/getting-started/running-reactpy.rst
This command shows how to run a ReactPy application configured with Flask using the Gunicorn WSGI server. It assumes the application instance is named 'app' and is defined in a file named 'main.py'.
```bash
gunicorn main:app
```
--------------------------------
### Integrate ReactPy into Existing ASGI Apps with Middleware
Source: https://context7.com/reactive-python/reactpy/llms.txt
The `ReactPyMiddleware` class facilitates the integration of ReactPy components into existing ASGI applications such as FastAPI or Starlette. It allows specifying root components and a path prefix for accessing them. This enables a seamless blend of Python-based ReactPy UIs with existing API frameworks.
```python
from fastapi import FastAPI
from reactpy import component, html
from reactpy.executors.asgi import ReactPyMiddleware
# Define components
@component
def Counter():
from reactpy import use_state
count, set_count = use_state(0)
return html.div(
html.h2(f"Count: {count}"),
html.button({"onClick": lambda e: set_count(count + 1)}, "Increment")
)
@component
def Dashboard():
return html.div(
html.h1("Dashboard"),
Counter()
)
# Create FastAPI app
fastapi_app = FastAPI()
@fastapi_app.get("/api/data")
async def get_data():
return {"data": "Hello from FastAPI!"}
# Wrap with ReactPy middleware
app = ReactPyMiddleware(
fastapi_app,
root_components=[
"myapp.components.Counter",
"myapp.components.Dashboard"
],
path_prefix="/_reactpy/",
)
# Components are now available at:
# /_reactpy/myapp.components.Counter/
# /_reactpy/myapp.components.Dashboard/
```
--------------------------------
### Updating Dictionaries in ReactPy (Immutable Methods)
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/adding-interactivity/dangers-of-mutability/index.rst
This Python code provides examples of how to update dictionary items in ReactPy without mutating the original dictionary. It shows the use of dictionary unpacking and the merge operator (Python 3.9+) as alternatives to item assignment or `dict.update()`.
```python
{**d, "key": value}
```
```python
# Python >= 3.9
d | {"key": value}
```
--------------------------------
### Using Identical Keys for Non-Sibling Elements in ReactPy
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/creating-interfaces/rendering-data/index.rst
Shows how ReactPy allows the use of identical keys when the elements are not siblings (i.e., they have different parent elements). This example uses two separate `` elements, each with list items sharing the same set of keys.
```python
from reactpy.core.elements import html
data_1 = [
{"id": 1, "text": "Something"},
{"id": 2, "text": "Something else"},
]
data_2 = [
{"id": 1, "text": "Another thing"},
{"id": 2, "text": "Yet another thing"},
]
html.section(
html.ul([html.li(data["text"], key=data["id"]) for data in data_1]),
html.ul([html.li(data["text"], key=data["id"]) for data in data_2]),
)
```
--------------------------------
### Respond to Button Click Event in ReactPy
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/adding-interactivity/index.rst
This example demonstrates how to attach an event handler to a button in ReactPy. When the button is clicked, a synchronous function is executed to print a message to the console. This showcases basic event binding and the use of closures to access component scope.
```python
from reactpy import html, run
def button_prints_message():
def handle_event(event):
print("button clicked!")
return html.button({"on_click": handle_event}, "Click Me")
run(button_prints_message())
```
--------------------------------
### JavaScript Build Configuration (Rollup)
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/escape-hatches/distributing-javascript.rst
Defines the input, output, and plugins for the Rollup build process. It specifies the entry point, the output file path within the Python package, the output format as ES Module, and includes plugins for module resolution, CommonJS compatibility, and environment variable replacement.
```javascript
export default {
input: "src/index.js",
output: {
file: "../your_python_package/bundle.js",
format: "esm",
},
plugins: [
resolve(),
commonjs(),
replace({
"process.env.NODE_ENV": JSON.stringify("production"),
}),
]
};
```
--------------------------------
### Loading JavaScript Modules in ReactPy
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/escape-hatches/distributing-javascript.rst
Demonstrates how to load a bundled JavaScript module into a Python application using ReactPy. It shows how to create a web module from a file and then export specific components from that module for use in Python.
```python
from pathlib import Path
import reactpy
_BUNDLE_PATH = Path(__file__).parent / "bundle.js"
_WEB_MODULE = reactpy.web.module_from_file(
# Note that this is the same name from package.json - this must be globally
# unique since it must share a namespace with all other javascript packages.
name="YOUR-PACKAGE-NAME",
file=_BUNDLE_PATH,
# What to temporarily display while the module is being loaded
fallback="Loading...",
)
# Your module must provide a named export for YourFirstComponent
YourFirstComponent = reactpy.web.export(_WEB_MODULE, "YourFirstComponent")
# It's possible to export multiple components at once
YourSecondComponent, YourThirdComponent = reactpy.web.export(
_WEB_MODULE, ["YourSecondComponent", "YourThirdComponent"]
)
```
--------------------------------
### Adding State Variable in ReactPy
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/adding-interactivity/components-with-state/index.rst
This code snippet demonstrates how to add a state variable to a ReactPy component. It shows the initialization of the state and how it can be updated, typically in response to user interactions like button clicks. The example focuses on managing an index for displaying sequential data.
```python
from pynecone.components.tags import Tag
from pynecone.vars import Var
def add_state_variable():
return Tag.create(
"",
{
"child": "Click me!",
"on_click": "setState({'count': count + 1})"
}
)
# Assume 'count' is a state variable initialized elsewhere
# Example usage:
# count = Var.create(0)
# button = add_state_variable()
```
--------------------------------
### Render data-driven list with keys in ReactPy
Source: https://github.com/reactive-python/reactpy/blob/main/docs/source/guides/creating-interfaces/index.rst
Shows how to render dynamic lists of UI elements based on data collections in ReactPy. It highlights the importance of using 'keys' for proper organization and efficient updates when dealing with sorted or filtered data.
```python
from reactpy import component, html
from typing import List, Dict
@component
def TodoListWithKeys(todos: List[Dict[str, str]]):
return html.ul(
# Items must be identified with unique keys!
[html.li(todo["text"]) for todo in todos]
)
defApp():
return html.div(
html.h1("My Todo List with Keys"),
TodoListWithKeys(todos=[
{"text": "Design a cool new app", "key": "0"},
{"text": "Build it", "key": "1"},
{"text": "Share it with the world!", "key": "2"}
])
)
```