Code components

Draw a component with your own React code. It runs on the web page and shows as a picture on the canvas.

Some things are easier to write than to draw: a counter, a chart fed by data, a carousel with its own logic. A code component is an ordinary component that a React module draws on the web page.

Draw a component with React code · 0:06
Description

A frame above the website template's first screen, made a component and selected. In the Design panel's Code section, New code module opens the editor with a starter React component that reads the component's size. With the editor closed, the canvas shows a picture of what the code draws in place of the component's layers.

  1. Select a component (or an instance of one) and open the Design panel's Code section.
  2. Click New code module. The editor opens with a starter component.
  3. Write your component and click Apply (or press ⌘ Enter). The editor says what the module exports, or why it does not compile.
  4. Close the editor. The canvas shows a picture of what the code draws, and the web preview runs it.

What the code is given

Each export of a module is a React component. It is given the design component's properties as props, by name: a property called Button label is buttonLabel. After those come width and height, the size of the instance.

import { useState } from 'react'
 
export default function Counter({ label, width, height }) {
  const [count, setCount] = useState(0)
  return (
    <button style={{ width, height }} onClick={() => setCount(count + 1)}>
      {label}: {count}
    </button>
  )
}

Change a property on an instance and that instance is drawn again with the new value. A module with several exports can draw several components: pick the export under Drawn by.

On the canvas

Code never runs in the editor itself. A hidden, sandboxed frame draws the component once and hands back a picture, which the canvas shows like any image. The picture is taken again when the source, a property or the size changes.

Until the picture is ready, and when the code fails, the component's own layers show. Keep a simple version of the component there: it is also what an SVG or PDF export uses, since those cannot run code.

Packages

A module can import react. To use another package, list it under Packages it may import with an exact version, one per line:

clsx@2.1.1

Packages are fetched from a CDN when the page runs, at exactly that version. A module cannot import other files or reach the network on its own.

For the agent

The agent writes code components with edit_code and attaches them with set_component_code; get_code reads what is there.