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