Path: blob/main/examples/reference/custom_components/ReactComponent.ipynb
2011 views
ReactComponent
simplifies the creation of custom Panel components by allowing you to write standard React code without the need to pre-compile or requiring a deep understanding of Javascript build tooling.
:::{note} ReactComponent
extends the JSComponent
class, which allows you to create custom Panel components using JavaScript.
ReactComponent
bears similarities to AnyWidget
and IpyReact
, but ReactComponent
is specifically optimized for use with Panel and React.
If you are looking to create custom components using Python and Panel component only, check out Viewer
. :::
API
ReactComponent Attributes
_esm
(str | PurePath): This attribute accepts either a string or a path that points to an ECMAScript module. The ECMAScript module should export arender
function which returns the HTML element to display. In a development environment such as a notebook or when using--dev
, the module will automatically reload upon saving changes. You can useJSX
andTypeScript
. The_esm
script is transpiled on the fly using Sucrase. The global namespace contains aReact
object that provides access to React hooks._importmap
(dict | None): This optional dictionary defines an import map, allowing you to customize how module specifiers are resolved._stylesheets
(List[str | PurePath] | None): This optional attribute accepts a list of CSS strings or paths to CSS files. It supports automatic reloading in development environments.
:::note You may specify a path to a file as a string instead of a PurePath. The path should be specified relative to the file its specified in. :::
render
Function
The _esm
attribute must export the render
function. It accepts the following parameters:
model
: Represents the Parameters of the component and provides methods to add (and remove) event listeners using.on
and.off
, render child React components using.get_child
, get a state hook for a parameter value using.useState
and to.send_event
back to Python.view
: The Bokeh view.el
: The HTML element that the component will be rendered into.
Any React component returned from the render
function will be appended to the HTML element (el
) of the component.
State Hooks
The recommended approach to build components that depend on parameters in Python is to create useState
hooks by calling model.useState('<parameter>')
. The model.useState
method returns an array with exactly two values:
The current state. During the first render, it will match the initialState you have passed.
The set function that lets you update the state to a different value and trigger a re-render.
Using the state value in your React component will automatically re-render the component when it is updated.
Callbacks
The model.on
and model.off
methods allow registering event handlers inside the render function. This includes the ability to listen to parameter changes and register lifecycle hooks.
Change Events
The following signatures are valid when listening to change events:
.on('<parameter>', callback)
: Allows registering an event handler for a single parameter..on(['<parameter>', ...], callback)
: Allows adding an event handler for multiple parameters at once..on('change:<parameter>', callback)
: Thechange:
prefix allows disambiguating change events from lifecycle hooks should a parameter name and lifecycle hook overlap.
The change:
prefix allows disambiguating change events from lifecycle hooks should a parameter name and lifecycle hook overlap.
Bidirectional Events
JS -> Python
.send_event('<name>', DOMEvent)
: Allows sending browserDOMEvent
to Python and associating it with a name. An event handler can be registered by name with the.on_event
method or by implementing a_handle_<name>
method on the class..send_msg(data)
: Allows sending arbitrary data to Python. An event handler can be registered with the.on_msg(callback)
method on the Python component or by implementing a_handle_msg
method on the class.
Python -> JS
._send_event(ESMEvent, data=msg)
: Allows sending arbitrary data to the frontend, which can be observed by registering a handler with.on('msg:custom', callback)
.
Lifecycle Hooks
.on('after_layout', callback)
: Called whenever the layout around the component is changed..on('after_render', callback)
: Called once after the component has been fully rendered..on('resize', callback)
: Called after the component has been resized..on('remove', callback)
: Called when the component view is being removed from the DOM.
The lifecycle:
prefix allows disambiguating lifecycle hooks from change events should a parameter name and lifecycle hook overlap.
Usage
Styling with CSS
Include CSS within the _stylesheets
attribute to style the component. The CSS is injected directly into the component's HTML.
Send Events from JavaScript to Python
Events from JavaScript can be sent to Python using the model.send_event
method. Define a handler in Python to manage these events. A handler is a method on the form _handle_<name-of-event>(self, event)
:
You can also define and send arbitrary data using the .send_msg()
API and by implementing a _handle_msg
method on the component:
Send Events from Python to JavaScript
Equivalently, events from Python can be sent to JavaScript using the ReactComponent._send_msg
method. To define a handler to receive these messages register a callback with model.on('msg:custom', callback)
:
In this simple example, we send a message containing the current date and time and display it in the component (note the serializer turns our datetime object into a timestamp):
Sending messages as events rather than state changes provides more control over state synchronization between Python and JavaScript.
Dependency Imports
JavaScript dependencies can be directly imported via URLs, such as those from esm.sh
.
Use the _importmap
attribute for more concise module references.
See import map for more info about the import map format.
External Files
You can load JSX and CSS from files by providing the paths to these files.
Create the file counter_button.py.
Now create the file counter_button.jsx.
Now create the file counter_button.css.
Serve the app with panel serve counter_button.py --dev
.
You can now edit the JSX or CSS file, and the changes will be automatically reloaded.
Try changing
count is {value}
toCOUNT IS {value}
and observe the update.Try changing the background color from
#0072B5
to#008080
.
Displaying A Single Child
You can display Panel components (Viewable
s) by defining a Child
parameter.
Lets start with the simplest example
If you provide a non-Viewable
child it will automatically be converted to a Viewable
by pn.panel
:
If you want to allow a certain type of Panel components only you can specify the specific type in the class_
argument.
The class_
argument also supports a tuple of types:
Displaying a List of Children
You can also display a List
of Viewable
objects using the Children
parameter type:
:::note You can change the item_type
to a specific subtype of Viewable
or a tuple of Viewable
subtypes. :::
Rendering into a specific DOM element
You can render the component into a specific DOM element by providing a root_node
to the underlying ReactComponent
model. This allows you to render things outside of the regular DOM hierarchy.
The root_node
should be a valid CSS selector for the DOM element you want to render into, if it doesn't exist it will be created and appended to the document body.
In this example we render the component into a div with the id custom-root
which we then place in the upper right corner of the document.
Using React Hooks
The global namespace also contains a React
object that provides access to React hooks. Here is an example of a simple counter button using the useState
hook: