Skip to main content

Embed and interact with React components from NiceGUI, in Python.

Project description

NiceGUI React Integration

PyPI version Python versions Downloads License: MIT GitHub stars

Embed and interact with React components from NiceGUI, in Python.

Live dashboard demo — a React recharts component whose data is streamed from Python

Everything above is a single NiceGUI page. The chart and list on the right are a React component (built on recharts); the controls on the left are plain Python (NiceGUI). Moving a Python control updates the React chart instantly, live data streams in through a ui.timer, and adding/removing a metric sends an event back to Python — see the complex example.

nicegui-react builds your React project with Vite, serves the compiled bundle as a static asset, and mounts it inside a native NiceGUI component. Props flow from Python to React, and events flow from React back to Python - both over NiceGUI's regular websocket channel.

Features

  • Easy integration - drop a React component into any NiceGUI page.
  • Reactive props - update props from Python (timers, events, background tasks, bindings) and the React component re-renders immediately. This works in every mode, not just during development.
  • Events - handle events emitted from React in your Python code (sync or async handlers).
  • Multiple components & instances per page - render as many different React projects, and as many instances of each, on a single page as you like. Each bundle is isolated.
  • Automatic bundling - your React code is built with Vite into a single, self-contained ES module.
  • Fast, content-addressed caching - builds are skipped when nothing changed, and the served URL changes only when the bundle content changes, so browsers never serve a stale bundle.
  • Live reload (dev mode) - edit your React code and see the change in the browser without restarting your Python app.

Installation

pip install nicegui-react

Requirements

  • Python 3.8+
  • NiceGUI 2.3+ (works with NiceGUI 2.x and 3.x)
  • Node.js and npm (used to build the React project)

Usage

from nicegui import ui
from nicegui_react import React


@ui.page("/")
def index():
    with ui.card():
        ui.label("Here is the React component:")

        react = (
            React(
                react_project_path="./my_react_project",
                main_component="App",  # your main component's name
            )
            .props(title="Hello from Python!")
            .on("onClick", lambda data: ui.notify(f"React said: {data}"))
        )

        ui.button("Update from Python", on_click=lambda: react.props(title="Updated!"))


ui.run()

Your React component receives the props you pass from Python, plus a handler function for every event you register with .on(...):

export default function App({ title, onClick }) {
  return (
    <div>
      <h3>{title}</h3>
      <button onClick={() => onClick({ clickedAt: Date.now() })}>Click me</button>
    </div>
  );
}

Parameters

  • react_project_path (str): path to your React project directory, resolved relative to the calling Python file.
  • main_component (str): name of the main React component to render.
  • component_id (str, optional): identifier for the component (defaults to the project folder name). Used to key the build cache.
  • env (dict, optional): environment variables exposed to the React app at build time as process.env.*.
  • use_legacy_peer_deps (bool, optional): pass --legacy-peer-deps to npm install.
  • dev (bool, optional): enable development mode with live reload (see below).

Methods

  • props(**kwargs): merge and update the props passed to the React component. Returns self for chaining.
  • on(event_name, handler): register a handler for an event emitted from React. The handler is called with the event payload. Returns self for chaining.
  • React.prebuild(react_project_path, main_component, ...) (classmethod): build and cache a project ahead of time so the first page visit does not pay the build cost. Arguments match the constructor. Call it from app.on_startup:
from nicegui import app
from nicegui_react import React

@app.on_startup
def _build_react():
    React.prebuild("./my_react_project", "App")

Development mode (live reload)

Pass dev=True to build your project in place and watch it for changes. When you edit a source file, Vite rebuilds and the component hot-reloads in the browser without a page refresh (current props are preserved):

React("./my_react_project", "App", dev=True)

In dev mode the following files are generated inside your project (add them to .gitignore):

.nicegui_react_dist/         # Vite build output
.nicegui_react/              # build metadata
_nicegui_react_main.jsx      # generated entry point
_nicegui_react_vite.config.mjs
package-lock.json            # if npm created it

In normal (non-dev) mode, none of these are written into your project. The build happens in a cache directory under ~/.nicegui/react_cache/.

How it works

  1. Your project is copied into a cache directory (or built in place in dev mode).
  2. A small entry module and a Vite config are generated. The entry exports a mount() function and imports your component.
  3. Vite builds a single, self-contained ES module (bundle.js) with React bundled in, plus a single bundle.css.
  4. The bundle is served as a static file, and a native NiceGUI Vue component dynamically imports it and mounts your component into its own DOM element.
  5. Props are passed as reactive component props; events are forwarded via the component's native event mechanism. No polling, no custom HTTP endpoints.

Because each component gets its own isolated bundle and its own element, any number of different components and instances can coexist on one page.

Setting up your React project

  • Place your React project in a directory relative to your Python script.
  • Your main component should be exported (default or named export both work).
  • A package.json with react, react-dom, vite and @vitejs/plugin-react is recommended. If it is missing or incomplete, nicegui-react will fill in sensible defaults and run npm install for you.

See the examples/ folder for complete demos:

  • app.py - two different React components (a counter and a clock), multiple instances of each on one page, timer-driven props, and events.
  • complex_app.py - a live dashboard built on the third-party recharts library, showing that arbitrary npm dependencies are bundled automatically. It streams array data from a ui.timer into a chart, keeps React-internal state (a controlled input) alongside Python-driven props, handles multiple events with different payloads, and uses an async Python event handler.

Upgrading from 0.1.x

Version 0.2.0 rewrites the internals for performance and correctness while keeping the public API (React(...), .props(), .on()) unchanged. No changes are required to your Python code or your React projects. Notable internal changes:

  • The bundle now loads as an ES module instead of being injected inline over the websocket.
  • Events use NiceGUI's native event system; the internal /react_event/* HTTP endpoint is gone.
  • Builds run in production mode by default (smaller, faster bundles).
  • Multiple different components and multiple instances per page are now supported.
  • The wrapper element no longer uses component_id as its DOM id (this is what enables multiple instances). If you targeted that id from external CSS/JS, style your React component from within its own bundle instead.

License

MIT. See the LICENSE file for details.

Contributing

Contributions are welcome. Please fork the repository and open a pull request from a feature branch.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nicegui_react-0.2.1.tar.gz (18.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nicegui_react-0.2.1-py3-none-any.whl (16.3 kB view details)

Uploaded Python 3

File details

Details for the file nicegui_react-0.2.1.tar.gz.

File metadata

  • Download URL: nicegui_react-0.2.1.tar.gz
  • Upload date:
  • Size: 18.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.2

File hashes

Hashes for nicegui_react-0.2.1.tar.gz
Algorithm Hash digest
SHA256 8f1056397f6f0f0e5dc0772f6e5daa7f2ecc48c226766cd28d550da052eada2f
MD5 69680901451b0ab1eb31c65c8ff55c72
BLAKE2b-256 938b3b6140f560968b9f5eba225e434b6e3fce522bbdd5f79d4486ee12653b3d

See more details on using hashes here.

File details

Details for the file nicegui_react-0.2.1-py3-none-any.whl.

File metadata

  • Download URL: nicegui_react-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 16.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.2

File hashes

Hashes for nicegui_react-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ff760ac0a1d2292999f130174910d73633a464eb8a00d22eefbd2420b39379b1
MD5 bcf20887a134372ef25426221710712f
BLAKE2b-256 9d166f209bd800920685c4c5114a78678b0664c2fbbf7f90326249ce0e41055b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page