Package: ipyreact
ipyreactReact for ipywidgets that just works. No webpack, no npm, no hassle. Just write jsx, tsx and python.Build on top ofAnyWidget.WhyIpyreact 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 asMaterial UI,Ant Designand evenReact-three-fiber.TutorialThis tutorial will walk you through the steps of building a complete ipywidget with react.Just click the JupyterLite or Binder link to start the interactive walkthrough.GoalsTake anyMaterial UI example, copy/paste the code, and it should work in Jupyter Notebook, Jupyter Lab, Voila, and more specifically,Solara.Wrap a library such asAnt Designgiving the options to customize any JSON<->JavaScript Object (de)serialization, such as theDatePickerwhich 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).ExamplesInline codeimportipyreactclassConfettiWidget(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()(NOTE: in the recording we used on_value, we now use setValue)Hot reloadingCreate 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:importipyreactimportpathlibclassConfettiWidget(ipyreact.ValueWidget):_esm=pathlib.Path("confetti.tsx")ConfettiWidget()Now edit, save, and see the changes in your browser/notebook.(NOTE: in the recording we used on_value, we now use setValue)IPython magicFirst load the ipyreact extension:%load_extipyreactThen use the%%reactmagic 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.valuecontains the number of clicks):(NOTE: in the recording we used on_value, we now use setValue)InstallationYou can install usingpip:pipinstallipyreactUsageSummaryTheValueWidgethas anvaluetrait, which is atraitlets.Anytrait. 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).Theipyreact.Widgetdoes not have thevaluetrait.All traits are added as props to your react component (e.g.{value, setValue...}pairs in the example above.For every traitipyreactautomatically provides aset<Traitname>callback, which you can use to set the trait value from your react component (e.g.setValuein the example above). (Note: we usedon_valuebefore, this is now deprecated)Props can de passed asWidget(props={"title": "My title"}), and contrary to a trait, will not add asetTitlecallable to the props.Children can be passed usingWidget(children=['text', or_widget])supporting text, widgets, and un-interrupted rendering of ipyreact widgets.Your code gets transpiled usingsucrasein the frontend, no bundler needed.Your code should be written in ES modules.Set_debug=Trueto 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.Passevents={"onClick": handler}to the constructor or add a method with the nameevent_onClick(self, data=None)to add aonClickcallback to your props.HTML elementsYou do not need to provide the module code to create built-in HTML elements, ipyreact supports the same API asReact's createElementallowing creation of buttons for instance.importipyreactipyreact.Widget(_type="button",children=["click me"])Note that in addition to all native browser elements, also web components are supported.ChildrenAs shown in the above example, we also support children, which supports a list of strings (text),ipyreact.Widgetwidgets that will be rendered as an uninterrupted react tree, or
any otheripywidgetsimportipyreactimportipywidgetsaswidgetsipyreact.Widget(_type="div",children=["normal text",ipyreact.Widget(_type="button",children=["nested react widgets"]),widgets.FloatSlider(description="regular ipywidgets")])EventsEvents can be passed via the event argument. In this caseonClickwill be added as a prop to the button element.importipyreactipyreact.Widget(_type="button",children=["click me"],events={"onClick":print})Subclasses can also add anevent_onClickmethod, which will also add aonClickevent handler to the props.Importing external modulesWriting 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 usehttps://esm.sh/which exposes many JS libraries as ES modules that
we can directly import.importipyreactipyreact.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 mapsHowever, 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 supportimport mapsto
write code more independant of where the modules come from.
You can provide an import map usingipyreact.define_import_map, which takes a dictionary of module names to urls or other modules. By default we supportreactandreact-domwhich is prebundled.Apart fromreact, 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 addexternal=react,react-domfor ReactJS based libraries, otherwiseesm.shwould import ReactJS again.Which means we can now write our ConfettiButton as:importipyreact# note that this import_map is already part of the defaultipyreact.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 pastemostof the examples frommui%%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 thehttps://github.com/guybedford/es-module-shimsshim 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 modulesCreating the ES moduleWhile 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 forhttps://ant.design/First create a simple file calledantd-minimal.jsthat exports what we need.export{Button,Flex,Slider}from"antd";Next, we install the libraries:$npminstallantdAnd 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=esnextNow we can define the module with a custom name (we call it antd-minimal).importipyreactfrompathlibimportPathipyreact.define_module("antd-minimal",Path("./antd-minimal.esm.js"))We can now use the components from this module:defon_click(event_data):w.children=["Clicked"]w=ipyreact.Widget(_module="antd-minimal",_type="Button",children=["Hi there"],events={"onClick":on_click})wOr, 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}),])stackInput components might need a little bit of custom code, and subclassingValueWidget. 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 caseonChange) to thesetValuefunction.importtraitletsclassSlider(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)sNote 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 beonChange={(event) => setValue(event.target.value)}.Now the slider widget is stateful, and we have bi-directional communication using the.valuetrait.
For instance, we can read it:s.valueOr write to it, and it will be reflected directly in the UI.s.value=10Test this out in the notebook:Bundled ES modules for threejsSee this notebook for a 3D WebGL threejs-fiber exampleDevelopment InstallationCreate a dev environment:condacreate-nipyreact-dev-cconda-forgenodejsyarnpythonjupyterlab
condaactivateipyreact-devInstall the python. This will also build the TS package.pipinstall-e".[test, examples, dev]"pre-commitinstallWhen 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 buildFor classic notebook, you need to run:jupyter nbextension install --sys-prefix --symlink --overwrite --py ipyreact
jupyter nbextension enable --sys-prefix --py ipyreactNote that the--symlinkflag doesn't work on Windows, so you will here have to run
theinstallcommand 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 changesTypescript: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 neededyarnrunwatch# Run JupyterLab in another terminaljupyterlabAfter 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.FAQWhich 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'suseContextto 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 errorFor instance, if you see"Cannot read properties of null (reading 'useReducer')"it means that you are loading in your own ReactJS version.If you usehttps://esh.sh, make sure you add??external=react,react-domat 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-domflags on the CLI.