Embed a cell in react, without downloading notebook first

Hi there,
I’m wondering if it is possible to embed a cell in react without downloading the notebook first, and if anyone has an example of how to do this.

This notebook is great (https://observablehq.com/@observablehq/how-to-embed-a-notebook-in-a-react-app) but I’d like to use the embed code provide at the cell level (described here https://observablehq.com/@observablehq/downloading-and-embedding-notebooks) and embed so that the viz in react updates when I’ve updated the cell on observables. Is that even possible (I’m new to react)?

Hey @mbrownshoes, it’s possible to embed Observable notebooks into a React app without having to download it by using Dynamic imports. When you download the code for a notebook, that link is an ES Module, meaning with vanilla JS you could do something like this from a browser:

import('https://api.observablehq.com/@d3/bar-chart.js?v=3').then(({default:define})=>{
  runtime.module(define, name => {
    if (name === "chart") 
      return new Inspector(document.body);
  })
})

However, when it comes to React specifically, using import() is different. Most React bundlers will override dynamic imports for it’s own React-specific usecase, and I’ve never been able to figure out how to use the “normal” dynamic import in the standard create-react-app (if anyone knows how, I’d love to hear how!)

As a workaround, you could use eval() around your import statement, which you can see in this CodePen, but this is extremely unsafe if you accept user-input here. Copy with caution!

2 Likes

Thanks for your thoughts @asg017 I’m not sure why it’s unsafe but sounds like something I should avoid. I’ll stick with downloading for now, until I hear of something a little more full proof. Cheers

This part is important:

You’ll want to avoid arbitrary code execution. Using eval() (or new Function()) is perfectly fine if you have full control over the eval’d code.

3 Likes