This documentation is still under construction 🚧. We welcome your feedback!

ReactPy#

ReactPy is a library for building user interfaces in Python without Javascript. ReactPy interfaces are made from components which look and behave similarly to those found in ReactJS. Designed with simplicity in mind, ReactPy can be used by those without web development experience while also being powerful enough to grow with your ambitions.

At a Glance#

To get a rough idea of how to write apps in ReactPy, take a look at the tiny “hello world” application below:

from reactpy import component, html, run


@component
def App():
    return html.h1("Hello, world!")


run(App)

Hint

Try clicking the 🚀 result tab to see what this displays!

So what exactly does this code do? First, it imports a few tools from reactpy that will get used to describe and execute an application. Then, we create an App function which will define the content the application displays. Specifically, it displays a kind of HTML element called an h1 section heading. Importantly though, a @component decorator has been applied to the App function to turn it into a component. Finally, we run a development web server by passing the App component to the run() function.

Note

See Running ReactPy in Production to learn how to use a production-grade server to run ReactPy.

Learning ReactPy#

This documentation is broken up into chapters and sections that introduce you to concepts step by step with detailed explanations and lots of examples. You should feel free to dive into any content that seems interesting. While each chapter assumes knowledge from those that came before, when you encounter a concept you’re unfamiliar with you should look for links that will help direct you to the place where it was originally taught.

Chapter 1 - Getting Started#

If you want to follow along with examples in the sections that follow, you’ll want to start here so you can install ReactPy. This section also contains more detailed information about how to run ReactPy in different contexts. For example, if you want to embed ReactPy into an existing application, or run ReactPy within a Jupyter Notebook, this is where you can learn how to do those things.

_images/install-and-run-reactpy.gif
_images/reactpy-in-jupyterlab.gif

Read More

Install ReactPy and run it in a variety of different ways - with different web servers and frameworks. You’ll even embed ReactPy into an existing app.

Chapter 2 - Creating Interfaces#

ReactPy is a Python package for making user interfaces (UI). These interfaces are built from small elements of functionality like buttons text and images. ReactPy allows you to combine these elements into reusable “components”. In the sections that follow you’ll learn how these UI elements are created and organized into components. Then, you’ll use this knowledge to create interfaces from raw data:

from reactpy import component, html, run


@component
def DataList(items, filter_by_priority=None, sort_by_priority=False):
    if filter_by_priority is not None:
        items = [i for i in items if i["priority"] <= filter_by_priority]
    if sort_by_priority:
        items = sorted(items, key=lambda i: i["priority"])
    list_item_elements = [html.li({"key": i["id"]}, i["text"]) for i in items]
    return html.ul(list_item_elements)


@component
def TodoList():
    tasks = [
        {"id": 0, "text": "Make breakfast", "priority": 0},
        {"id": 1, "text": "Feed the dog", "priority": 0},
        {"id": 2, "text": "Do laundry", "priority": 2},
        {"id": 3, "text": "Go on a run", "priority": 1},
        {"id": 4, "text": "Clean the house", "priority": 2},
        {"id": 5, "text": "Go to the grocery store", "priority": 2},
        {"id": 6, "text": "Do some coding", "priority": 1},
        {"id": 7, "text": "Read a book", "priority": 1},
    ]
    return html.section(
        html.h1("My Todo List"),
        DataList(tasks, filter_by_priority=1, sort_by_priority=True),
    )


run(TodoList)

Read More

Learn to construct user interfaces from basic HTML elements and reusable components.

Chapter 3 - Adding Interactivity#

Components often need to change what’s on the screen as a result of an interaction. For example, typing into the form should update the input field, clicking a “Comment” button should bring up a text input field, clicking “Buy” should put a product in the shopping cart. Components need to “remember” things like the current input value, the current image, the shopping cart. In ReactPy, this kind of component-specific memory is created and updated with a “hook” called use_state() that creates a state variable and state setter respectively:

import json
from pathlib import Path

from reactpy import component, hooks, html, run

HERE = Path(__file__)
DATA_PATH = HERE.parent / "data.json"
sculpture_data = json.loads(DATA_PATH.read_text())


@component
def Gallery():
    index, set_index = hooks.use_state(0)

    def handle_click(event):
        set_index(index + 1)

    bounded_index = index % len(sculpture_data)
    sculpture = sculpture_data[bounded_index]
    alt = sculpture["alt"]
    artist = sculpture["artist"]
    description = sculpture["description"]
    name = sculpture["name"]
    url = sculpture["url"]

    return html.div(
        html.button({"on_click": handle_click}, "Next"),
        html.h2(name, " by ", artist),
        html.p(f"({bounded_index + 1} of {len(sculpture_data)})"),
        html.img({"src": url, "alt": alt, "style": {"height": "200px"}}),
        html.p(description),
    )


run(Gallery)
[
  {
    "name": "Homenaje a la Neurocirugía",
    "artist": "Marta Colvin Andrade",
    "description": "Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.",
    "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/22/Homenaje_a_la_Neurocirug%C3%ADa%2C_Instituto_de_Neurocirug%C3%ADa%2C_Providencia%2C_Santiago_20200106_02.jpg/1024px-Homenaje_a_la_Neurocirug%C3%ADa%2C_Instituto_de_Neurocirug%C3%ADa%2C_Providencia%2C_Santiago_20200106_02.jpg",
    "alt": "A bronze statue of two crossed hands delicately holding a human brain in their fingertips."
  },
  {
    "name": "Eternal Presence",
    "artist": "John Woodrow Wilson",
    "description": "Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as \"a symbolic Black presence infused with a sense of universal humanity.\"",
    "url": "https://upload.wikimedia.org/wikipedia/commons/6/6f/Chicago%2C_Illinois_Eternal_Silence1_crop.jpg",
    "alt": "The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity."
  },
  {
    "name": "Moai",
    "artist": "Unknown Artist",
    "description": "Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.",
    "url": "https://upload.wikimedia.org/wikipedia/commons/5/50/AhuTongariki.JPG",
    "alt": "Three monumental stone busts with the heads that are disproportionately large with somber faces."
  },
  {
    "name": "Blue Nana",
    "artist": "Niki de Saint Phalle",
    "description": "The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.",
    "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Blue_Nana_-_panoramio.jpg/1024px-Blue_Nana_-_panoramio.jpg",
    "alt": "A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy."
  },
  {
    "name": "Cavaliere",
    "artist": "Lamidi Olonade Fakeye",
    "description": "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
    "url": "https://upload.wikimedia.org/wikipedia/commons/3/34/Nigeria%2C_lamidi_olonade_fakeye%2C_cavaliere%2C_1992.jpg",
    "alt": "An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns."
  },
  {
    "name": "Big Bellies",
    "artist": "Alina Szapocznikow",
    "description": "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
    "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/KMM_Szapocznikow.JPG/200px-KMM_Szapocznikow.JPG",
    "alt": "The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures."
  },
  {
    "name": "Terracotta Army",
    "artist": "Unknown Artist",
    "description": "The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.",
    "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/2015-09-22-081415_-_Terrakotta-Armee%2C_Grosse_Halle.jpg/1920px-2015-09-22-081415_-_Terrakotta-Armee%2C_Grosse_Halle.jpg",
    "alt": "12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor."
  },
  {
    "name": "Lunar Landscape",
    "artist": "Louise Nevelson",
    "description": "Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.",
    "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/72/1999-3-A--J_s.jpg/220px-1999-3-A--J_s.jpg",
    "alt": "A black matte sculpture where the individual elements are initially indistinguishable."
  },
  {
    "name": "Aureole",
    "artist": "Ranjani Shettar",
    "description": "Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a \"fine synthesis of unlikely materials.\"",
    "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/50/Shettar-_5854-sm_%285132866765%29.jpg/399px-Shettar-_5854-sm_%285132866765%29.jpg",
    "alt": "A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light."
  },
  {
    "name": "Hippos",
    "artist": "Taipei Zoo",
    "description": "The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.",
    "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e3/Hippo_sculpture_Taipei_Zoo_20543.jpg/250px-Hippo_sculpture_Taipei_Zoo_20543.jpg",
    "alt": "A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming."
  }
]

In ReactPy, use_state, as well as any other function whose name starts with use, is called a “hook”. These are special functions that should only be called while ReactPy is rendering. They let you “hook into” the different capabilities of ReactPy’s components of which use_state is just one (well get into the other later).

Read More

Learn how user interfaces can be made to respond to user interaction in real-time.

Chapter 4 - Managing State#

Read More

Under construction 🚧

Chapter 5 - Escape Hatches#

Read More

Under construction 🚧

Chapter 6 - Understanding ReactPy#

Read More

Under construction 🚧