Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท Custom Components

Custom Components: How They Work

Understand Gradio custom components: the gradio cc workflow, backend class with preprocess and postprocess, Svelte frontend, data models and publishing, with a runnable component stand-in.

Gradio ships with dozens of components, but sometimes you need one that does not exist: a color wheel, a 3D model viewer, a rich-text editor, a PDF viewer. Custom components let you build your own, package it like a normal Python library and use it in any app as gr.Something or from my_package import Something.

The gradio cc tools, Node.js and Svelte are not available on this site, so the commands and Svelte code below are read-only. The runnable blocks reproduce the data flow, the part that is pure Python, in a labelled stand-in.

The big picture

A component has two halves that talk through JSON:

flowchart LR
    B["Browser<br/>Svelte frontend<br/>(Index.svelte)"] -- "value as JSON" --> P["preprocess()"]
    P --> F["Your function<br/>fn(value)"]
    F --> Q["postprocess()"]
    Q -- "JSON" --> B

The frontend holds the on-screen value; the Python class converts it to and from what your function wants.

  • The backend is a Python class that inherits from gradio.components.Component (or an existing component). Its preprocess turns the value sent by the browser into a Python object for your function; postprocess turns your function's return value into something the browser can display.
  • The frontend is a Svelte project that draws the component, reports user edits and receives updates.

The workflow

Terminal
pip install gradio                      # plus Node.js 20 or newer on your PATH
gradio cc create ColorWheel --template SimpleTextbox   # scaffold a project
cd colorwheel
gradio cc dev                           # live-reload demo while you edit
gradio cc build                         # build a wheel for distribution
gradio cc publish                       # upload to PyPI (and optionally a Space)

create generates a folder with these parts:

TEXT
colorwheel/
  backend/colorwheel/colorwheel.py   # the Python class
  frontend/Index.svelte              # how it looks in an app
  frontend/Example.svelte            # how it looks in the examples table
  demo/app.py                        # a demo using the component
  pyproject.toml                     # package metadata and dependencies

Templates such as SimpleTextbox, Textbox, Image, Audio or Video copy an existing component, so you start from working code instead of a blank page. The workflow needs Node.js because the frontend is compiled to JavaScript that is shipped inside the Python wheel; users of your package only need Python.

The backend class

A minimal backend looks like this:

Python
from gradio.components import Component
from gradio.data_classes import GradioModel

class ColorValue(GradioModel):
    hex: str
    alpha: float = 1.0

class ColorWheel(Component):
    data_model = ColorValue
    EVENTS = ["change", "input", "submit"]

    def __init__(self, value: str | None = "#ff0000", *, label: str | None = None, **kwargs):
        super().__init__(value=value, label=label, **kwargs)

    def preprocess(self, payload: ColorValue | None) -> str | None:
        return payload.hex if payload else None

    def postprocess(self, value: str | None) -> ColorValue | None:
        return ColorValue(hex=value) if value else None

    def api_info(self):
        return {"type": "string", "description": "a hex color such as #aabbcc"}

    def example_payload(self):
        return {"hex": "#00ff00", "alpha": 1.0}

    def example_value(self):
        return "#00ff00"

Key parts:

  • data_model describes the JSON the browser sends and receives. Using a model rather than a plain dict gives validation and documentation in the API panel.
  • EVENTS lists which events users can attach handlers to (color.change(...)).
  • preprocess/postprocess convert in each direction. Your function never sees ColorValue, only a string.
  • api_info, example_payload, example_value feed the "Use via API" panel and the examples table.

The frontend in brief

Index.svelte receives props such as value, label, interactive and gradio. A tiny version:

SVELTE
<script lang="ts">
  import type { Gradio } from "@gradio/utils";
  export let value = { hex: "#ff0000", alpha: 1 };
  export let label = "Color";
  export let gradio: Gradio<{ change: never; input: never }>;
  $: value, gradio.dispatch("change");
</script>

<label>{label}
  <input type="color" bind:value={value.hex} on:input={() => gradio.dispatch("input")} />
</label>

Setting value updates the Python side when an event fires, and gradio.dispatch("change") triggers handlers you attached in Python. You do not need to write network code: Gradio sends and receives the value for you.

Simulating the data flow

The next block implements the same pattern without Gradio: a base class, a data model, preprocess and postprocess, and a pipeline that mimics a button click. It is a stand-in for how data crosses the browser boundary.

Python preprocess and postprocess in plain Python

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The function only ever sees "#ff8800" and returns "#7f4400". The component wraps and unwraps the JSON. Returning "orange" raises an error in postprocess, which in Gradio becomes an error message in the UI, the reason strict postprocess code saves debugging time.

Using and sharing the component

Once built, a component installs like any package:

Terminal
pip install gradio_colorwheel
Python
import gradio as gr
from gradio_colorwheel import ColorWheel

with gr.Blocks() as demo:
    c = ColorWheel(label="Pick")
    out = gr.Textbox()
    c.change(lambda v: f"You picked {v}", c, out)

Publish with gradio cc publish, which also creates a documentation Space from your demo. Name packages gradio_<name> by convention, add a clear README and version them with semantic versioning, since apps pin your package.

When not to build a component

Most needs are met without one: gr.HTML with custom markup, CSS and JavaScript (see themes, CSS and JS), or composing existing components in Blocks. Build a component only when you need a new interactive widget with its own value and events, or want to share one across several apps.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does preprocess do in a custom component?

    preprocess runs before your function; postprocess runs on its return value.
  2. 2. Which language is the component frontend written in?

    The browser side is a Svelte project built with Node.js.
  3. 3. Which command creates a new component project?

    gradio cc create scaffolds the backend, frontend and demo folders.
  4. 4. What is EVENTS used for?

    EVENTS names the events like change or submit that handlers can be bound to.

Summary

  • A custom component is a Python backend class plus a Svelte frontend, packaged as a wheel.
  • preprocess and postprocess translate between browser JSON and your function's values.
  • gradio cc create, dev, build and publish cover the full workflow; Node.js is needed only for the builder.
  • Prefer gr.HTML, CSS and composition unless you need a genuinely new widget.

Next: Themes, CSS and JavaScript