Skip to content
Daniel Krol edited this page Dec 31, 2024 · 5 revisions

Tips for making and packaging Sandstorm apps with React. Integrating Sandstorm, etc.

As of this writing it's only one but we could dump them all here.

Creating an offer template

The instructions for HTTP APIs shows how to make an "offer template", where you create a frame and Sandstorm fills it with a message that includes an API key for the user to copy. React apps are built in a special way. Components get loaded dynamically, sometimes jsx files are used instead of plain js. We'll make a couple adjustments to make it work.

Start by making sandstorm.jsx in an appropriate place within the project. In our example we'll put it in the app/ directory:

export function requestIframeURL() {
  var template = "You can use the $API_TOKEN key to reach me at $API_HOST.";
  window.parent.postMessage({renderTemplate: {
    rpcId: "0",
    template: template,
    clipboardButton: 'left'
  }}, "*");
}

var copyIframeURLToElement = function(event) {
  if (event.data.rpcId === "0") {
    if (event.data.error) {
      console.log("ERROR: " + event.data.error);
    } else {
      var el = document.getElementById("offer-iframe");
      el.setAttribute("src", event.data.uri);
    }
  }
};

window.addEventListener("message", copyIframeURLToElement);

It's basically the example code from the docs with a small difference: the original version calls requestIframeURL when the DOM loads. For React, we need to wait for the component to load. We export requestIframeURL, and we can call it after the component loads using useEffect. We put the <frame> tag within the return statement, and set the style using a particular syntax (we can't just use a string like with HTML).

In our component directory (let's say components/MyComponents.jsx):

import { requestIframeURL } from "../app/sandstorm";

...

const ExampleComponent = () => {
  useEffect(() => {
    requestIframeURL()
  })
  return (
    ...
        <iframe style={{ height: "55px", width: "100%", margin: 0, border: 0 }} id="offer-iframe">
        </iframe>
    ...
  );
};

There seem to be specific rules about where the <iframe> tag can be placed among the other tags. You'll get some errors if you get it wrong, but try playing with it. Find other standard HTML tags and see if it works next to those.

Clone this wiki locally