Embedding Bokeh into a ReactJS app using BokehJS

Bokeh is best known for interactive data exploration using Python. It is however also easily possible to embed your visualisation inside an ReactJS app.

To do this we will first use a Python backend to create a JSON representation of our plot, and BokehJS on the frontend to render it.

An example of visulations made using Bokeh curtesy of Bokeh.org

As first step we create a simple Bokeh plot like we usually would using Python:

https://gist.github.com/sonium0/c5a17c691b3b07bb47cd048b91065b91

This will create the following plot:

Simple plot created by Bokeh

Now that we have checked that everything looks as expected it is time to create the output that we need for our frontend. For this Bokeh provides us with the json_item function to which we will pass our figure object p from before:

https://gist.github.com/sonium0/20f5b695c2eebfe4a55e4c61b4fdabba

In a productive environment we now need to use a backend server like Flask or Django to serve the JSON output generated here to the our React frontend.

Now it is time adapt our frontend that I have set up using create-react-app. Lets install BokehJS using either yarn or npm:

yarn add @bokeh/bokehjs

npm install @bokeh/bokehjs

We can then modify App.js (truncated for clarity):

https://gist.github.com/sonium0/6eb2ec86421425b64f0a0061364eb711

For testing we can just copy&paste the JSON output from python, replace the None values by null and assign it to the item variable.

The useEffect hook prevents that the embed_item is executed on every render and only executed once. Otherwise we end up with multiple plots instead of one. Note that the JSON object has been truncated for readability, but you can find the complete code here. The result looks like this:

Bokeh plot inside create-react-app

To sum it up, we have shown that we can embed a bokeh plot super easily in ReactJS.

Unlike in great tutorial of David Vasallo the solution here doesn’t need CDN imports. If you want to see how this can be integrated with for example Flask, I recommend David Vasallo’s tutorial which shows exactly this step.

Comments are closed.