Skip to main content

React for ipywidgets that just works

Project description

ipyreact

React for ipywidgets that just works. No webpack, no npm, no hassle. Just write jsx, tsx and python.

Build on top of AnyWidget.

Why

Ipyreact adds composability, allowing you to add children to your widget, which will render the whole react tree in a single react context, without adding extra divs or creating a new react context.

This allows wrapping libraries such as Material UI, Ant Design and even React-three-fiber.

Tutorial

This tutorial will walk you through the steps of building a complete ipywidget with react.

JupyterLight Binder

Just click the JupyterLite or Binder link to start the interactive walkthrough.

Goals

  • Take any Material UI example, copy/paste the code, and it should work in Jupyter Notebook, Jupyter Lab, Voila, and more specifically, Solara.
  • Wrap a library such as Ant Design giving the options to customize any JSON<->JavaScript Object (de)serialization, such as the DatePicker which uses a dayjs object internally, which cannot be serialized over the wire to Python.
  • Compose widgets together to form a single react tree, with the same react context (e.g. useContext).

Examples

Inline code

import ipyreact


class ConfettiWidget(ipyreact.ValueWidget):
    _esm = """
    import confetti from "canvas-confetti";
    import * as React from "react";

    export default function({value, setValue}) {
        return <button onClick={() => confetti() && setValue(value + 1)}>
            {value || 0} times confetti
        </button>
    };"""
ConfettiWidget()

initial-30-fps-compressed

(NOTE: in the recording we used on_value, we now use setValue)

Hot reloading

Create a tsx file:

// confetti.tsx
import confetti from "canvas-confetti";
import * as React from "react";

export default function ({ value, setValue }) {
  return (
    <button onClick={() => confetti() && setValue(value + 1)}>
      {value || 0} times confetti
    </button>
  );
}

And use it in your python code:

import ipyreact
import pathlib


class ConfettiWidget(ipyreact.ValueWidget):
    _esm = pathlib.Path("confetti.tsx")

ConfettiWidget()

Now edit, save, and see the changes in your browser/notebook.

hot-reload-compressed

(NOTE: in the recording we used on_value, we now use setValue)

IPython magic

First load the ipyreact extension:

%load_ext ipyreact

Then use the %%react magic to directly write jsx/tsx in your notebook:

%%react
import confetti from "canvas-confetti";
import * as React from "react";

export default function({value, setValue}) {
    return <button onClick={() => confetti() && setValue(value + 1)}>
        {value || 0} times confetti
    </button>
};

Access the underlying widget with the name _last_react_widget (e.g. _last_react_widget.value contains the number of clicks):

magic-optimized

(NOTE: in the recording we used on_value, we now use setValue)

Installation

You can install using pip:

pip install ipyreact

Usage

Summary

  • The ValueWidget has an value trait, which is a traitlets.Any trait. Use this to pass data to your react component, or to get data back from your react component (since it inherits from ipywidgets.ValueWidget it can be used in combination with ipywidgets' interact).
  • The ipyreact.Widget does not have the value trait.
  • All traits are added as props to your react component (e.g. {value, setValue...} pairs in the example above.
  • For every trait ipyreact automatically provides a set<Traitname> callback, which you can use to set the trait value from your react component (e.g. setValue in the example above). (Note: we used on_value before, this is now deprecated)
  • Props can de passed as Widget(props={"title": "My title"}), and contrary to a trait, will not add a setTitle callable to the props.
  • Children can be passed using Widget(children=['text', or_widget]) supporting text, widgets, and un-interrupted rendering of ipyreact widgets.
  • Your code gets transpiled using sucrase in the frontend, no bundler needed.
  • Your code should be written in ES modules.
  • Set _debug=True to get more debug information in the browser console.
  • Make sure you export a default function from your module (e.g. export default function MyComponent() { ... }). This is the component that will be rendered.
  • Pass events={"onClick": handler} to the constructor or add a method with the name event_onClick(self, data=None) to add a onClick callback to your props.

HTML elements

You do not need to provide the module code to create built-in HTML elements, ipyreact supports the same API as React's createElement allowing creation of buttons for instance.

import ipyreact
ipyreact.Widget(_type="button", children=["click me"])

Note that in addition to all native browser elements, also web components are supported.

Children

As shown in the above example, we also support children, which supports a list of strings (text), ipyreact.Widget widgets that will be rendered as an uninterrupted react tree, or any other ipywidgets

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")
])

JupyterLight Binder

Events

Events can be passed via the event argument. In this case onClick will be added as a prop to the button element.

import ipyreact
ipyreact.Widget(_type="button", children=["click me"], events={"onClick": print})

Subclasses can also add an event_onClick method, which will also add a onClick event handler to the props.

JupyterLight Binder

Importing external modules

Writing JSX code without having to compile/bundle is great, but so is using external libraries.

Ipyreact uses ES modules, which allows native importing of external libraries when written as an ES module. In the example below, we use https://esm.sh/ which exposes many JS libraries as ES modules that we can directly import.

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 <button onClick={() => confetti() && setValue(value + 1)}>
            {value || 0} times confetti
        </button>
    };
    """
)

Import maps

However, the above code now has a direct link to "https://esm.sh/canvas-confetti@1.6.0" which makes the code very specific to esm.sh.

To address this, we also support import maps to write code more independant of where the modules come from. You can provide an import map using ipyreact.define_import_map, which takes a dictionary of module names to urls or other modules. By default we support react and react-dom which is prebundled.

Apart from react, the default we provide is:

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",
})

Note that it is important to add external=react,react-dom for ReactJS based libraries, otherwise esm.sh would import ReactJS again.

Which means we can now write our ConfettiButton as:

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 <button onClick={() => confetti() && setValue(value + 1)}>
            {value || 0} times confetti
        </button>
    };
    """
)

And it also means we can copy paste most of the examples from mui

%%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 (
    <Button
      variant="contained"
      onClick={() => confetti() && setValue(value + 1)}
    >
      {value || 0} times confetti
    </Button>
  );
}

We use the https://github.com/guybedford/es-module-shims shim to the browser page for the import maps functionality. This also means that although import maps can be configured per widget, they configuration of import maps is global.

Bundled ESM modules

Creating the ES module

While esm.sh is convenient to use, for production use, we recommend creating a standalone bundle. This will load faster and will not require a direct connection to esm.sh, which might not be available in airgapped or firewalled environments.

We will not create a minimal bundle for https://ant.design/

First create a simple file called antd-minimal.js that exports what we need.

export { Button, Flex, Slider } from "antd";

Next, we install the libraries:

$ npm install antd

And use ESBuild to turn this into a self-contained module/bundle, without react, since ipyreact provides that for us.

$ npx esbuild ./antd-minimal.js --bundle --outfile=./antd-minimal.esm.js --format=esm --external:react --external:react-dom --target=esnext

Now we can define the module with a custom name (we call it antd-minimal).

import ipyreact
from pathlib import Path

ipyreact.define_module("antd-minimal", Path("./antd-minimal.esm.js"))

We can now use the components from this module:

def on_click(event_data):
    w.children = ["Clicked"]

w = ipyreact.Widget(_module="antd-minimal", _type="Button", children=["Hi there"], events={"onClick": on_click})
w

Or, composing multiple ones:

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

Input components might need a little bit of custom code, and subclassing ValueWidget. It often means binding the value to the right prop of the input component (in this case the Slider takes the same name, value) and coupling the event handler (in this case onChange) to the setValue function.

import traitlets


class Slider(ipyreact.ValueWidget):
    _esm = """
    import * as React from "react";
    import {Slider} from "antd-minimal"

    export default ({value, setValue, ...rest}) => {
        return <Slider value={value} onChange={(v) => setValue(v)} {...rest}/>
    }

    """
s = Slider(value=2)
s

Note that it depends on the implementation of the event handler if the value is being passed directly, or a (synthetic) event with the data will be passed as argument. An typical example event handler could be onChange={(event) => setValue(event.target.value)}.

Now the slider widget is stateful, and we have bi-directional communication using the .value trait. For instance, we can read it:

s.value

Or write to it, and it will be reflected directly in the UI.

s.value = 10

Test this out in the notebook: JupyterLight Binder

Bundled ES modules for threejs

See this notebook for a 3D WebGL threejs-fiber example

JupyterLight Binder

Development Installation

Create a dev environment:

conda create -n ipyreact-dev -c conda-forge nodejs yarn python jupyterlab
conda activate ipyreact-dev

Install the python. This will also build the TS package.

pip install -e ".[test, examples, dev]"
pre-commit install

When developing your extensions, you need to manually enable your extensions with the notebook / lab frontend. For lab, this is done by the command:

jupyter labextension develop --overwrite .
yarn run build

For classic notebook, you need to run:

jupyter nbextension install --sys-prefix --symlink --overwrite --py ipyreact
jupyter nbextension enable --sys-prefix --py ipyreact

Note that the --symlink flag doesn't work on Windows, so you will here have to run the install command every time that you rebuild your extension. For certain installations you might also need another flag instead of --sys-prefix, but we won't cover the meaning of those flags here.

How to see your changes

Typescript:

If you use JupyterLab to develop then you can watch the source directory and run JupyterLab at the same time in different terminals to watch for changes in the extension's source and automatically rebuild the widget.

# Watch the source directory in one terminal, automatically rebuilding when needed
yarn run watch
# Run JupyterLab in another terminal
jupyter lab

After a change wait for the build to finish and then refresh your browser and the changes should take effect.

Python:

If you make a change to the python code then you will need to restart the notebook kernel to have it take effect.

FAQ

Which version of React do you use.

We currently only support React 18. Although we have some scaffolding in place to support different version, we do not have funding to support both.

Why does ipyreact provides React?

If several ReactJS components need to be composed into a single React app, they need to share the same React context. This makes it possible for features such as React's useContext to work across the whole React tree. If every library brings its own React, they cannot communicate using this. Also, every child would need to be nested in its own <div> which can affect the layout of your application. When ipyreact provides React, we can build a true ReactJS application with a normal/true React render tree.

I get a React error

For instance, if you see "Cannot read properties of null (reading 'useReducer')" it means that you are loading in your own ReactJS version.

If you use https://esh.sh, make sure you add ??external=react,react-dom at the end of the url, so that your esm bundle doesn't include its own ReactJS version, but uses the one provided with ipyreact.

If you make your own bundle using esbuild, make sure to add the --external:react --external:react-dom flags on the CLI.

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

ipyreact-0.4.1.tar.gz (1.9 MB view hashes)

Uploaded Source

Built Distribution

ipyreact-0.4.1-py3-none-any.whl (1.3 MB view hashes)

Uploaded Python 3

Supported by

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