### 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 `