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.

ReactPyはPythonでReactのようなコンポーネントベースのユーザーインターフェイスを構築するためのフレームワークです。以下に初心者向けの使い方をシンプルに説明します。


1. インストール方法

ReactPyをインストールするには、次のコマンドをターミナルで実行します。

pip install reactpy[starlette]

starletteは、シンプルなサーバーのための依存ライブラリです。)


2. 最初のReactPyアプリケーションを作成する

次のコードをファイルに保存し、app.pyという名前をつけます。

from reactpy import component, html, run

@component
def HelloWorld():
    return html.h1("Hello, ReactPy!")

run(HelloWorld)

3. アプリケーションを実行する

ターミナルで次のコマンドを実行して、アプリケーションを起動します。

python app.py

出力されるURL(通常は http://127.0.0.1:8000)をブラウザで開くと、以下のテキストが表示されます。

Hello, ReactPy!

4. ReactPyの基本的なコンセプト

ReactPyはコンポーネントベースで動作します。コンポーネントとは、UIの小さな再利用可能なパーツです。

コンポーネントの定義例

from reactpy import component, html, run

@component
def Greeting(name):
    return html.div(
        html.h2(f"Hello, {name}!"),
        html.p("Welcome to ReactPy.")
    )

@component
def App():
    return html.div(
        Greeting("Alice"),
        Greeting("Bob"),
    )

run(App)

これで次のように表示されます。

Hello, Alice!
Welcome to ReactPy.

Hello, Bob!
Welcome to ReactPy.

5. 状態(state)の管理

ReactPyではコンポーネント内で状態を管理できます。

from reactpy import component, html, run, use_state

@component
def Counter():
    count, set_count = use_state(0)

    def increment(event):
        set_count(count + 1)

    return html.div(
        html.h1(f"Count: {count}"),
        html.button({"on_click": increment}, "Increment"),
    )

run(Counter)

これでボタンをクリックするとカウンターが増えていきます。


以上がReactPyを始めるための基本的な使い方です。慣れてきたら、公式ドキュメントをさらに読み進め、より複雑な機能にも挑戦してみてください。


投稿日

カテゴリー:

投稿者:

タグ: