### Installing ipyreact and Dependencies for Development Source: https://github.com/widgetti/ipyreact/blob/master/README.md This bash command installs ipyreact in editable mode with test, examples, and dev extras, and sets up pre-commit hooks. ```bash pip install -e ".[test, examples, dev]" pre-commit install ``` -------------------------------- ### Install ipyreact Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Installs the ipyreact library. This is a prerequisite for using ipyreact features. ```python %pip install -q ipyreact # This line is for JupyterLite (if this takes more than 10 seconds, something probably hung, restart the kernel and run this cell again) ``` -------------------------------- ### Install ipyreact with pip Source: https://github.com/widgetti/ipyreact/blob/master/docs/source/index.rst Install the ipyreact library using pip. This is the standard method for Python package installation. ```bash pip install ipyreact ``` -------------------------------- ### Install JupyterLab Extension Source: https://github.com/widgetti/ipyreact/blob/master/docs/source/develop-install.rst Install the ipyreact JupyterLab extension. This command should be run from the root of the cloned repository. ```bash jupyter labextension install . ``` -------------------------------- ### Installing Three.js Fiber Libraries Source: https://github.com/widgetti/ipyreact/blob/master/examples/threejs-fiber/threejs-fiber.ipynb Installs the specified versions of @react-three/drei and @react-three/fiber. Ensure these versions are compatible with your project. ```bash $ npm install @react-three/drei@9.68.6 @react-three/fiber@8.13.0 ``` -------------------------------- ### Install JupyterLab Extension Source: https://github.com/widgetti/ipyreact/blob/master/docs/source/installing.rst If you are using JupyterLab, install the ipyreact extension using this command. ```bash jupyter labextension install jupyter-react ``` -------------------------------- ### Install Jupyter Notebook Extension (Classic Notebook) Source: https://github.com/widgetti/ipyreact/blob/master/docs/source/installing.rst For classic Jupyter Notebook versions older than 5.3, install the front-end extension using this command. Choose the appropriate flag (--sys-prefix, --user, or --system) based on your environment. ```bash jupyter nbextension install [--sys-prefix / --user / --system] --py ipyreact ``` -------------------------------- ### Installing ipyreact Source: https://github.com/widgetti/ipyreact/blob/master/examples/antd/antd.ipynb Install the ipyreact library, which is necessary for integrating React components within a Jupyter environment. This command is particularly relevant for JupyterLite installations. ```python %pip install -q ipyreact # This line is needed for JupyterLite ``` -------------------------------- ### Install Jupyter Notebook Extension (Symlink) Source: https://github.com/widgetti/ipyreact/blob/master/docs/source/develop-install.rst Install the ipyreact Jupyter Notebook extension using a symlink for development. Choose the appropriate flag (--sys-prefix, --user, or --system) based on your environment. ```bash jupyter nbextension install [--sys-prefix / --user / --system] --symlink --py ipyreact ``` -------------------------------- ### Enable Jupyter Notebook Extension (Classic Notebook) Source: https://github.com/widgetti/ipyreact/blob/master/docs/source/installing.rst After installation, enable the front-end extension for classic Jupyter Notebook using this command. Ensure you use the same flag as in the installation command. ```bash jupyter nbextension enable [--sys-prefix / --user / --system] --py ipyreact ``` -------------------------------- ### Install ipyreact with conda Source: https://github.com/widgetti/ipyreact/blob/master/docs/source/index.rst Install the ipyreact library using conda. This is an alternative installation method, often preferred for managing complex dependencies. ```bash conda install ipyreact ``` -------------------------------- ### Dynamic Scene with Solara and ipyreact Source: https://github.com/widgetti/ipyreact/blob/master/examples/threejs-fiber/threejs-fiber.ipynb Build a dynamic 3D scene using Solara's reactive variables and ipyreact components. This example demonstrates adding and clearing boxes on a canvas, controlling the scene with OrbitControls, and setting up lighting. Ensure 'random' and 'random_color' are defined or imported. ```python boxes = solara.reactive([ ([-1, 0, 3], "#18a36e"), ([1, 0, 3], "#f56f42"), ]) def add(event_data=None): x = random.random() * 4 - 2 z = random.random() * 4 - 1 color = random_color() # Call the random_color function to get a random color boxes.value = [*boxes.value, ([x, 0, z], color)] def clear(): boxes.value = boxes.value[:2] def add_10(): for i in range(10): add() @solara.component def Page(): with solara.Row(): solara.Button("Clear", on_click=clear) solara.Button("Add 10", on_click=add_10) solara.Markdown("Click to add a new box") with Div(style={"height": "600px"}): # a canvas fill the available space, so we add a parent div with height with Canvas(events={"onClick": add}): for position, color in boxes.value: Box(position=position, color=color) OrbitControls() DirectionalLight(props=dict(color="#ffffff", intensity=1, position=[-1, 2, 4])) Page() ``` -------------------------------- ### Install ipyreact with Pip (Developer Mode) Source: https://github.com/widgetti/ipyreact/blob/master/docs/source/develop-install.rst Install the ipyreact package in editable mode using pip. This is useful for development as changes to the source code are reflected immediately. ```bash pip install -e . ``` -------------------------------- ### Using Ant Design Button Widget Source: https://github.com/widgetti/ipyreact/blob/master/examples/antd/antd.ipynb Instantiate and display an Ant Design Button widget using ipyreact. This example shows how to set initial children and attach an event handler for click events. ```python def on_click(event_data): w.children = ["Clicked"] w = ipyreact.Widget(_module="antd-minimal", _type="Button", children=["Hi there"], events={"onClick": on_click}) w ``` -------------------------------- ### Enabling Jupyter Notebook Extension for Development Source: https://github.com/widgetti/ipyreact/blob/master/README.md These commands install and enable a local ipyreact extension for the classic Jupyter Notebook. Note the Windows limitation regarding the --symlink flag. ```bash jupyter nbextension install --sys-prefix --symlink --overwrite --py ipyreact jupyter nbextension enable --sys-prefix --py ipyreact ``` -------------------------------- ### Customizing Widget Initialization with super() Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Extend widget functionality by overriding the `__init__` method and calling `super().__init__` to execute parent initialization logic. This example prints a message upon widget creation. ```python import ipyreact from traitlets import Int, signature_has_traits # 🪄🪄🪄 this is an advanced example, feel free to skip 🪄🪄🪄 @signature_has_traits class MyExampleWidget(ipyreact.Widget): def __init__(self, **kwargs): super().__init__(**kwargs) self.print_welcome_message() def print_welcome_message(self): print(f"Button was initilized with width of {self.my_width}px ") my_width = Int(23).tag(sync=True) _esm = """ import * as React from "react"; export default function MyButton({ my_width }) { return ( ); }""" MyExampleWidget(my_width=200) ``` -------------------------------- ### Importing External Modules with Direct URL Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Import external JavaScript libraries directly from a URL using ES modules. This example uses canvas-confetti from esm.sh. ```python import ipyreact ipyreact.ValueWidget( _esm=""" import confetti from "https://esm.sh/canvas-confetti@1.6.0"; import * as React from "react"; export default function({value, setValue}) { return }; """ ) ``` -------------------------------- ### Adding IDE Autocompletion with traitlets Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Use the `signature_has_traits` decorator to enable autocompletion for widget properties in IDEs. This example defines a widget with a synchronized integer traitlet. ```python import ipyreact from traitlets import Any, Unicode, Int, observe, signature_has_traits @signature_has_traits class MyExampleWidget(ipyreact.Widget): my_width = Int(23).tag(sync=True) _esm = """ import * as React from "react"; export default function MyButton({ my_width }) { return ( ); }""" MyExampleWidget(my_width=300) ``` -------------------------------- ### Create a ValueWidget with External Module and State Source: https://github.com/widgetti/ipyreact/blob/master/README.md Renders a button that uses an external JavaScript module for confetti effects and manages a click counter using React state. This example shows how to integrate external JS libraries and manage component state. ```python import ipyreact icyreact.ValueWidget( _esm=f""" import confetti from "https://esm.sh/canvas-confetti@1.6.0"; import * as React from "react"; export default function({{value, setValue}}) {{ return }}; """ ) ``` -------------------------------- ### Enabling Hot-Reloading for External Components Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Configure ipyreact to hot-reload components from external files by passing a Path object directly to '_esm'. This requires 'watchdog' to be installed and allows immediate reflection of file changes without re-running Python code. ```python import ipyreact import pathlib class WidgetFromFile(ipyreact.Widget): _esm = pathlib.Path("my_component.tsx") # <- this will not work in JupyterLite WidgetFromFile() ``` -------------------------------- ### React Component with Material-UI and Canvas-Confetti using Import Maps Source: https://github.com/widgetti/ipyreact/blob/master/README.md A React component example that utilizes Material-UI's Button and the canvas-confetti library. It assumes that import maps have been configured to resolve these modules, allowing for a clean import statement within the component. ```tsx %%react -n my_widget -d import {Button} from "@mui/material"; import confetti from "canvas-confetti"; import * as React from "react"; export default function({ value, setValue}) { console.log("value=", value); return ( ); } ``` -------------------------------- ### Composing Ant Design Widgets with Flex Source: https://github.com/widgetti/ipyreact/blob/master/examples/antd/antd.ipynb Create a layout using Ant Design's Flex component to arrange other Ant Design widgets vertically. This example includes a Button and a Slider within the Flex container. ```python stack = ipyreact.Widget(_module="antd-minimal", _type="Flex", props={"vertical": True, "style": {"padding": "24px"}}, children=[ ipyreact.Widget(_module="antd-minimal", _type="Button", children=["Ant Design Button"]), ipyreact.Widget(_module="antd-minimal", _type="Slider", props={"defaultValue": 3, "min": 0, "max": 11}), ]) stack ``` -------------------------------- ### Instantiate and Display Widget Source: https://github.com/widgetti/ipyreact/blob/master/examples/Observe_example.ipynb Creates an instance of the EvenOddWidget and displays it in the environment. ```python w = EvenOddWidget() w ``` -------------------------------- ### Setting up ipyreact Development Environment Source: https://github.com/widgetti/ipyreact/blob/master/README.md These bash commands set up a Conda environment for ipyreact development, including Node.js, Yarn, and JupyterLab. ```bash conda create -n ipyreact-dev -c conda-forge nodejs yarn python 'jupyterlab<4' conda activate ipyreact-dev ``` -------------------------------- ### Widget with Parameterized Message (F-string - Not Recommended) Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Demonstrates a naive approach to parameterizing a widget using f-strings. This method is discouraged due to potential syntax conflicts and inability to update values dynamically. ```python import ipyreact # ❌❌❌ WARNING: THIS CODEBLOCK IS NOT GOOD PRACTICE ❌❌❌ class MyExampleWidget(ipyreact.Widget): message = "Hello World" _esm = f""" import * as React from "react"; export default function MyButton() {{ return }}; ""MyExampleWidget() ``` -------------------------------- ### Create a Simple HTML Button Widget Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Creates a basic HTML button widget using ipyreact.Widget with specified type and children. ```python ipyreact.Widget(_type="button", children=["X"]) ``` -------------------------------- ### Watch Source Directory and Run JupyterLab (TypeScript) Source: https://github.com/widgetti/ipyreact/blob/master/README.md Use these commands to watch your TypeScript source directory for changes and run JupyterLab concurrently. Refresh your browser after builds to see changes. ```bash yarn run watch ``` ```bash jupyter lab ``` -------------------------------- ### Custom ReactWidget with Event Callbacks Source: https://github.com/widgetti/ipyreact/blob/master/examples/events.ipynb Shows how to create a custom `ReactWidget` with defined event handlers. Frontend event names (e.g., `on_click`) are automatically mapped to Python methods (e.g., `event_on_click`). ```python import ipyreact import traitlets class ButtonWithHandler(ipyreact.ReactWidget): # extra trait label = traitlets.Unicode("Click me").tag(sync=True) _esm = """ import * as React from "react"; export default function({on_click, on_pass_data, label}) { // make sure the arguments passed matches the // python function return \
}; """ # all on_* methods are automatically available from the frontend # with the same name as a prop def event_on_click(self): self.label = "Clicked" # an optional argument can be passed # an optional third argument can contain buffers (not used here) def event_on_pass_data(self, data): print(data) self.label = f'Clicked "Pass data" at {data["x"]},{data["y"]} when label was {data["label"]}' b = ButtonWithHandler(debug=True) b ``` -------------------------------- ### Basic Event Handling with print Source: https://github.com/widgetti/ipyreact/blob/master/examples/events.ipynb Demonstrates a simple way to attach an event handler to a widget. The `onClick` event is directly mapped to a Python `print` function. ```python import ipyreact ipyreact.Widget(_type="button", children=["click me"], events={"onClick": print}) ``` -------------------------------- ### Clone ipyreact Repository Source: https://github.com/widgetti/ipyreact/blob/master/docs/source/develop-install.rst Clone the ipyreact repository from GitHub to your local machine. ```bash git clone https://github.com/widgetti/ipyreact cd ipyreact ``` -------------------------------- ### Enabling JupyterLab Extension for Development Source: https://github.com/widgetti/ipyreact/blob/master/README.md These commands are used in JupyterLab development to enable a local extension build. It involves linking the extension and rebuilding the frontend. ```bash jupyter labextension develop --overwrite . yarn run build ``` -------------------------------- ### Solara Components for ipyreact Widgets Source: https://github.com/widgetti/ipyreact/blob/master/examples/threejs-fiber/threejs-fiber.ipynb Define custom Solara components that act as wrappers for ipyreact widgets. This allows for a more streamlined API and easier integration into Solara applications. Ensure necessary imports like 'solara' and 'ipyreact' are available. ```python import solara @solara.component def Box(position, color, props={}, events={}, children=[]): return BoxWidget.element(props={**props, **dict(color=color, position=position)}, events=events, children=children) @solara.component def Canvas(props={}, events={}, children=[]): return ipyreact.Widget.element(props=props, events=events, children=children, _type="Canvas", _module="threejs-fiber") @solara.component def OrbitControls(props={}, events={}, children=[]): return ipyreact.Widget.element(_type="OrbitControls", _module="threejs-fiber", props=props, events=events, children=children) @solara.component def DirectionalLight(props={}, events={}, children=[]): # starts with a lower case, should be available globally, so we don't need to pass # _module="threejs-fiber" return ipyreact.Widget.element(_type="directionalLight", props=props, events=events, children=children) @solara.component def Div(style={}, props={}, events={}, children=[]): # we use a ipyreact based div to avoid an extra wrapper div which will affect layout return ipyreact.Widget.element(_type="div", props={**props, **dict(style=style)}, children=children, events=events) ``` -------------------------------- ### Configuring the Three.js Canvas Widget Source: https://github.com/widgetti/ipyreact/blob/master/examples/threejs-fiber/threejs-fiber.ipynb Sets up the main 'Canvas' widget from Three.js Fiber, including initial boxes, orbit controls, and a directional light. It also configures click events to add new boxes dynamically. ```python canvas = ipyreact.Widget(_type="Canvas", _module="threejs-fiber", events=dict(onClick=add), children=[ BoxWidget(props=dict(position=[-1, 0, 3], color="#18a36e")), BoxWidget(props=dict(position=[1, 0, 3], color="#f56f42")), ipyreact.Widget(_type="OrbitControls", _module="threejs-fiber"), # seems that if it starts with a small letter, it's globally available, and not exported # from the threejs-fiber module, therefore we do not pass _module="threejs-fiber" ipyreact.Widget(_type="directionalLight", props=dict(color="#ffffff", intensity=1, position=[-1, 2, 4])) ] ) # the canvas fills the parent, so wrap it in a div with the fixed height ippyreact.Widget(_type="div", props=dict(style=dict(height="600px")), children=[canvas]) ``` -------------------------------- ### Create a Basic ipyreact Widget Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Converts a React component into an ipyreact widget by defining it within an _esm string in a class inheriting from ipyreact.Widget. ```python import ipyreact class MyExampleWidget(ipyreact.Widget): _esm = """ import * as React from "react"; export default function MyButton() { return ; }; """ MyExampleWidget(props={"message": "hi", "title": "Behaves like a tooltip"}, children=[' extra', ' children']) ``` -------------------------------- ### Load ipyreact IPython Extension Source: https://github.com/widgetti/ipyreact/blob/master/README.md Loads the ipyreact extension to enable the use of the %%react magic command in Jupyter notebooks. ```python %load_ext ipyreact ``` -------------------------------- ### Bundling Ant Design Components with ESBuild Source: https://github.com/widgetti/ipyreact/blob/master/README.md This bash command uses ESBuild to create a bundled ES module from 'antd-minimal.js'. It excludes React and targets modern JavaScript environments. ```bash $ npx esbuild ./antd-minimal.js --bundle --outfile=./antd-minimal.esm.js --format=esm --external:react --external:react-dom --target=esnext ``` -------------------------------- ### Loading React Component from External File Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Load the JavaScript component definition from an external file (e.g., 'my_component.tsx') using pathlib. This improves code organization and enables syntax highlighting. ```python import ipyreact import pathlib class WidgetFromFile(ipyreact.Widget): _esm = pathlib.Path("my_component.tsx").read_text() WidgetFromFile() ``` -------------------------------- ### Basic React Component with %react Magic Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Renders a simple React button component directly within a Jupyter notebook using the %%react cell magic. ```python %%react import * as React from "react"; export default function MyButton() { return ( < button > X < /button>); } ``` -------------------------------- ### Create a Button with an onClick Event Source: https://github.com/widgetti/ipyreact/blob/master/README.md Renders a button that triggers a Python print function when clicked. This demonstrates how to handle user events directly in Python. ```python import ipyreact icyreact.Widget(_type="button", children=["click me"], events={"onClick": print}) ``` -------------------------------- ### Exporting Ant Design Components Source: https://github.com/widgetti/ipyreact/blob/master/examples/antd/antd.ipynb Create a JavaScript file to export specific Ant Design components that will be included in the bundle. This file serves as the entry point for bundling. ```javascript export {Button, Flex, Slider} from 'antd'; ``` -------------------------------- ### Using an Ant Design Button Component Source: https://github.com/widgetti/ipyreact/blob/master/README.md This Python code demonstrates how to use a Button component from the custom 'antd-minimal' module within an ipyreact Widget. It includes an event handler for click events. ```python def on_click(event_data): w.children = ["Clicked"] w = ipyreact.Widget(_module="antd-minimal", _type="Button", children=["Hi there"], events={"onClick": on_click}) ``` -------------------------------- ### Create a Button HTML Element Source: https://github.com/widgetti/ipyreact/blob/master/README.md Renders a basic HTML button element using ipyreact. This is useful for creating simple interactive UI components. ```python import ipyreact icyreact.Widget(_type="button", children=["click me"]) ``` -------------------------------- ### Widget with Message Prop Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Creates a widget that accepts a 'message' prop from Python to display in the button. This allows dynamic updates from the Python side. ```python import ipyreact from traitlets import Unicode class MyExampleWidget(ipyreact.Widget): _esm = """ import * as React from "react"; export default function MyButton({ message }) { return ; }; ""MyExampleWidget(props={"message": "hi"}) ``` -------------------------------- ### Using Import Maps for Canvas-Confetti in ipyreact Source: https://github.com/widgetti/ipyreact/blob/master/README.md Demonstrates how to define an import map for 'canvas-confetti' within an ipyreact ValueWidget. This allows the widget's internal ESM code to import 'canvas-confetti' without a hardcoded URL, making the widget more portable. ```python import ipyreact # note that this import_map is already part of the default ipyreact.define_import_map({ "canvas-confetti": "https://esm.sh/canvas-confetti@1.6.0", }) ipyreact.ValueWidget( _esm=""" import confetti from "canvas-confetti"; import * as React from "react"; export default function({value, setValue}) { return }; """ ) ``` -------------------------------- ### Python Imports for ipyreact Source: https://github.com/widgetti/ipyreact/blob/master/examples/Observe_example.ipynb Imports necessary modules from ipyreact and traitlets for creating reactive widgets. ```python import ipyreact from traitlets import Int, observe, Unicode ``` -------------------------------- ### Apply CSS Styles to Widget Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Applies CSS rules to style the widget globally within the notebook. Note that clearing output removes these styles. ```python from IPython.display import HTML css_rules = """ .mybutton { background-color: yellow; border-radius: 10px; } """ HTML("") ``` -------------------------------- ### Use %%react Magic for Inline JSX Source: https://github.com/widgetti/ipyreact/blob/master/README.md Allows writing JSX/TSX code directly within a Jupyter notebook cell using the %%react magic command. The created widget is accessible via the _last_react_widget variable. ```python %%react import confetti from "canvas-confetti"; import * as React from "react"; export default function({value, setValue}) { return }; ``` -------------------------------- ### Forwarding Props and Children in React Component Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Demonstrates how to forward all unused props and children to a child element in a React component using object destructuring. This pattern preserves the ability to set standard HTML attributes. ```python import ipyreact from traitlets import Unicode ``` -------------------------------- ### Define Custom Button Component with Event Handler Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Create a custom button component that emits a custom 'onMyClick' event. The event handler in Python can optionally accept arguments passed from the component. ```python def on_my_click(new_label): w.children = [new_label] w = ipyreact.Widget(children=["Click me"], events={"onMyClick": on_my_click}, _esm=""" import * as React from "react"; export default function MyButton({ onMyClick, children }) { return ; }; """ ) w ``` -------------------------------- ### Defining a Custom ES Module in ipyreact Source: https://github.com/widgetti/ipyreact/blob/master/README.md This Python code registers a custom ES module named 'antd-minimal' with ipyreact, pointing to the generated bundle file. ```python import ipyreact from pathlib import Path i pyreact.define_module("antd-minimal", Path("./antd-minimal.esm.js")) ``` -------------------------------- ### Creating a Box Widget with Three.js Fiber Source: https://github.com/widgetti/ipyreact/blob/master/examples/threejs-fiber/threejs-fiber.ipynb Defines a React component 'Box' using Three.js Fiber syntax within an ipyreact widget. This component renders a mesh with box geometry and phong material, and animates its rotation. ```python from traitlets import default class BoxWidget(ipyreact.Widget): _esm = """ import React, { useRef, useState } from "react" import { Canvas, useFrame, useThree } from 'threejs-fiber' import { OrbitControls } from "threejs-fiber"; export default function Box({position, color}) { const ref = useRef() useFrame(() => (ref.current.rotation.x = ref.current.rotation.y += 0.01)) return ( ) } """ ``` -------------------------------- ### Create a Div with Nested Elements Source: https://github.com/widgetti/ipyreact/blob/master/README.md Renders a div element containing a mix of text, a nested button widget, and a regular ipywidget. This showcases hierarchical component composition. ```python import ipyreact import ipywidgets as widgets icyreact.Widget(_type="div", children=[ "normal text", ipyreact.Widget(_type="button", children=["nested react widgets"]), widgets.FloatSlider(description="regular ipywidgets") ]) ``` -------------------------------- ### Composing Ant Design Flex and Components Source: https://github.com/widgetti/ipyreact/blob/master/README.md This Python code shows how to compose multiple Ant Design components (Button and Slider) within a Flex container using ipyreact Widgets. ```python stack = ipyreact.Widget(_module="antd-minimal", _type="Flex", props={"vertical": True, "style": {"padding": "24px"}}, children=[ ipyreact.Widget(_module="antd-minimal", _type="Button", children=["Ant Design Button"]), ipyreact.Widget(_module="antd-minimal", _type="Slider", props={"defaultValue": 3, "min": 0, "max": 11}), ]) ``` -------------------------------- ### Create ipyreact Widget with Mixed Children Source: https://github.com/widgetti/ipyreact/blob/master/examples/children.ipynb This snippet creates a 'div' ipyreact Widget. It includes plain text, a nested ipyreact button Widget, and a standard ipywidgets FloatSlider as its children. Ensure ipyreact and ipywidgets are imported. ```python import ipyreact import ipywidgets as widgets ipyreact.Widget(_type="div", children=[ "normal text", ipyreact.Widget(_type="button", children=["nested react widgets"]), widgets.FloatSlider(description="regular ipywidgets") ]) ``` -------------------------------- ### EvenOddWidget with Observer Source: https://github.com/widgetti/ipyreact/blob/master/examples/Observe_example.ipynb Defines a custom ipyreact widget that synchronizes Python traitlets with a React component and observes changes to the 'count' traitlet to update a 'message' traitlet. ```python class EvenOddWidget(ipyreact.ReactWidget): #note that when we add these traitlets, they will automatically be made available to the react component message = Unicode("Click the button!").tag(sync=True) count = Int(0).tag(sync=True) #it is key that we also take the change argument, otherwise a hard to find python error will be thrown @observe('count') def _observe_count(self, change): self.message = "Yes ✅✅✅" if check_is_even(self.count) else "No 🧊🧊🧊" ``` -------------------------------- ### Define Custom Import Map for Material-UI and Canvas-Confetti Source: https://github.com/widgetti/ipyreact/blob/master/README.md Provides a custom import map configuration for Material-UI and canvas-confetti, specifying their URLs from esm.sh. It's crucial to include `external=react,react-dom` for React-based libraries to prevent duplicate React imports. ```python define_import_map({ "@mui/material": "https://esm.sh/@mui/material@5.11.10?external=react,react-dom", "@mui/material/": "https://esm.sh/@mui/material@5.11.10&external=react,react-dom/", "@mui/icons-material/": "https://esm.sh/@mui/icons-material/?external=react,react-dom", "canvas-confetti": "https://esm.sh/canvas-confetti@1.6.0", }) ``` -------------------------------- ### Defining a Custom ipyreact Module Source: https://github.com/widgetti/ipyreact/blob/master/examples/antd/antd.ipynb Define a custom module within ipyreact using the bundled JavaScript file. This makes the Ant Design components available for use as ipyreact widgets. ```python import ipyreact from pathlib import Path ippyreact.define_module("antd-minimal", Path("./antd-minimal.esm.js")) ``` -------------------------------- ### Adding State with Traitlets Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Manage component state by adding traitlets to the widget class. These traits are synchronized between Python and the frontend, providing both a value and a setter function. ```python import ipyreact from traitlets import Unicode class MyExampleWidget(ipyreact.Widget): message = Unicode("Click me").tag(sync=True) _esm = """ import * as React from "react"; export default function MyButton({ message, setMessage }) { return ; }; """ w = MyExampleWidget() ``` ```python w.message = "Set from Python 🐍" ``` ```python MyExampleWidget(message="Different initial value") ``` -------------------------------- ### Creating a Stateful Slider Widget Source: https://github.com/widgetti/ipyreact/blob/master/examples/antd/antd.ipynb Define a custom ipyreact widget subclassing `ValueWidget` for an Ant Design Slider. This enables bi-directional value binding and state management through the `.value` trait. ```python import traitlets class Slider(ipyreact.ValueWidget): _esm = """ import * as React from "react"; import {Slider} from "antd-minimal" export default ({value, setValue, ...rest}) => { return setValue(v)} {...rest}/> } " s = Slider(value=2) s ``` -------------------------------- ### Creating a Stateful Slider Widget with ipyreact Source: https://github.com/widgetti/ipyreact/blob/master/README.md This Python code defines a custom Slider widget subclassing ipyreact.ValueWidget. It uses an embedded ES module to integrate an Ant Design Slider with bidirectional value binding via traitlets. ```python import traitlets class Slider(ipyreact.ValueWidget): _esm = """ import * as React from "react"; import {Slider} from "antd-minimal" export default ({value, setValue, ...rest}) => { return setValue(v)} {...rest}/> } " s = Slider(value=2) ``` -------------------------------- ### Exporting Three.js Fiber Components Source: https://github.com/widgetti/ipyreact/blob/master/examples/threejs-fiber/threejs-fiber.ipynb Creates a self-contained ES module by exporting necessary components from @react-three/fiber and @react-three/drei. This is a prerequisite for bundling. ```javascript export * from '@react-three/fiber' export * from "@react-three/drei"; ``` -------------------------------- ### Create Confetti Widget from TSX File Source: https://github.com/widgetti/ipyreact/blob/master/README.md Defines a custom ipywidget using a React component written in a separate TSX file. This enables hot reloading, allowing changes in the TSX file to be reflected in the notebook without restarting the kernel. ```tsx // confetti.tsx import confetti from "canvas-confetti"; import * as React from "react"; export default function ({ value, setValue }) { return ( ); } ``` ```python import ipyreact import pathlib class ConfettiWidget(ipyreact.ValueWidget): _esm = pathlib.Path("confetti.tsx") ConfettiWidget() ``` -------------------------------- ### Subclassing ipyreact.Widget for Event Methods Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Define custom event handlers as methods prefixed with 'event_' within a subclass of ipyreact.Widget. These methods are automatically exposed as props to the React component. ```python class MyButton(ipyreact.Widget): _esm = """ import * as React from "react"; export default function MyButton({ onMyClick, children }) { return ; }; """ # the method name should match the name in the props def event_onMyClick(self, new_label): w.children = [new_label] w = MyButton(children=["Click me"]) w ``` -------------------------------- ### Handling Native Events Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Attach event handlers to widget components using the 'events' dictionary. Native browser events like 'onClick' can be mapped to Python callback functions. ```python def on_click(event_data): w.children = ["Clicked ⭐"] w = ipyreact.Widget(_type="button", children=["Click me"], props={ "title": "Behaves like a tooltip", "style": {"border": "5px solid orange"}, "class": "mybutton" }, events={"onClick": on_click}) w ``` -------------------------------- ### Defining ipyreact Module for Three.js Fiber Source: https://github.com/widgetti/ipyreact/blob/master/examples/threejs-fiber/threejs-fiber.ipynb Defines a custom ipyreact module named 'threejs-fiber' using the generated bundle file. This makes the Three.js Fiber components available within the Jupyter environment. ```python import ipyreact from pathlib import Path ippyreact.define_module("threejs-fiber", Path("./threejs-fiber.bundle.js")) ``` -------------------------------- ### Exporting Ant Design Components for a Minimal Bundle Source: https://github.com/widgetti/ipyreact/blob/master/README.md This JavaScript code defines an ES module that exports specific components from the 'antd' library. It's used as a source for creating a self-contained bundle. ```javascript export { Button, Flex, Slider } from "antd"; ``` -------------------------------- ### Using ValueWidget for Single Value Components Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Leverage ipyreact.ValueWidget for components that manage a single value. This provides a pre-defined 'value' trait and allows direct use with ipywidgets.interact. ```python import ipyreact from traitlets import Unicode ipyreact.ValueWidget(value="Similar, but using the value/ValueWidget", _esm=""" import * as React from "react"; export default function MyButton({ value, setValue }) { return ; }; """ ) ``` -------------------------------- ### Observing Traitlet Changes for Component Updates Source: https://github.com/widgetti/ipyreact/blob/master/examples/full_tutorial.ipynb Use the `@observe` decorator to react to changes in traitlet properties (like 'number') and update component state or messages. This is useful when events are tied to state changes. ```python from traitlets import Any, observe from traitlets import Int, Any import ipyreact def is_prime_number(n): for i in range(2, n): if n % i == 0: return False return True class PrimePythonWidget(ipyreact.Widget): message = Any("Click to test the next number").tag(sync=True) number = Int(0).tag(sync=True) @observe("number") def _observe_count(self, change): if is_prime_number(self.number): self.message = "Yes ✅ it is a prime number" else: self.message = "No ❌, not a primer number" # alternatively: # self.props = {**self.props, message: .... _esm = """ import * as React from "react"; // NOTE: we add setMessage, even though we do not use it, to avoid forwarding // it to button export default function({setNumber, number, message, setMessage, ...rest}) { return

{message}
};""" primepy = PrimePythonWidget(props={"class": "mybutton"}) primepy ``` -------------------------------- ### React Component for EvenOddWidget Source: https://github.com/widgetti/ipyreact/blob/master/examples/Observe_example.ipynb The React component definition for the EvenOddWidget, which receives props from the Python backend and includes a button to increment the count and display the message. ```javascript _esm = """ import confetti from "canvas-confetti"; import * as React from "react"; export default function({setCount, count, message}) { return

Is number even? {message}
}; """ ``` -------------------------------- ### Create Confetti Widget with Inline JSX Source: https://github.com/widgetti/ipyreact/blob/master/README.md Defines a custom ipywidget that displays a button to trigger a confetti animation. The React component is defined directly within the Python code using JSX. ```python import ipyreact class ConfettiWidget(ipyreact.ValueWidget): _esm = """ import confetti from "canvas-confetti"; import * as React from "react"; export default function({value, setValue}) { return }; """ ConfettiWidget() ``` -------------------------------- ### Generating Random Colors Source: https://github.com/widgetti/ipyreact/blob/master/examples/threejs-fiber/threejs-fiber.ipynb A utility function to generate random hexadecimal color codes. This is used to assign unique colors to dynamically added boxes. ```python import random def random_color(): # Generates a random hex color code return "#" + ''.join([random.choice('0123456789ABCDEF') for _ in range(6)]) ``` -------------------------------- ### Adding Dynamic Boxes to the Canvas Source: https://github.com/widgetti/ipyreact/blob/master/examples/threejs-fiber/threejs-fiber.ipynb Defines a function to add new Box widgets to the canvas with random positions and colors. This function is triggered by click events on the canvas. ```python def add(_ignore=None): x = random.random() * 4 - 2 z = random.random() * 4 - 1 color = random_color() # Call the random_color function to get a random color box = BoxWidget(props=dict(position=[x, 0, z], color=color)) # Use the random color for the box canvas.children = [*canvas.children, box] ``` -------------------------------- ### Even Number Check Function Source: https://github.com/widgetti/ipyreact/blob/master/examples/Observe_example.ipynb A simple Python function to determine if a number is even. ```python def check_is_even(number): if number %2 == 0: return True else: return False ``` -------------------------------- ### Updating Slider Widget Value Source: https://github.com/widgetti/ipyreact/blob/master/examples/antd/antd.ipynb Programmatically update the value of the custom stateful Slider widget. Changes to the `.value` trait are reflected in the UI, demonstrating bi-directional communication. ```python s.value = 10 ``` -------------------------------- ### Reading Slider Widget Value Source: https://github.com/widgetti/ipyreact/blob/master/examples/antd/antd.ipynb Access the current value of the custom stateful Slider widget. The `.value` trait reflects the slider's current position. ```python s.value ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.