For building rich user interfaces we use React, in this article, we will discuss a new Python library ReactPy to build the user interfaces.
The ReactJS library allows developers to create reusable UI components and manage the state of these components efficiently. Similarly, ReactPy is a library for building user interfaces in Python without Javascript. ReactPy interfaces are made using components. So we can easily build web GUI with ReactPy.
To install ReactPy run the following command :
pip install "reactpy[starlette]"
Here starlette is used as the backend. Le’s try a simple example.
from reactpy import component, html, run
@component
def HelloWorld():
return html.h1("Hello, World!")
run(HelloWorld)
Save the above content to main.py file and run it using the below command :
python main.py
Open the URL http://127.0.0.1:8000 in the browser. We can see the “hello world” message.
So what is a component in ReactPy?
As per the ReactPy documentation, components are normal Python functions and it returns HTML. In order to make a component just add @component decorator to the top of the function. See the below example :
@component
def Title():
return html.h1("Nolowiz")
The above function title is a ReactPy component.
We can use multiple components to create a complex one see the below code.
from reactpy import component, html, run
@component
def Title(title):
return html.h1(title)
@component
def Photo():
return html.img(
{
"src": "https://picsum.photos/id/152/500/300",
"style": {"width": "30%"},
}
)
@component
def PhotographerName(caption):
return html.h4(caption)
@component
def PhotoViewer():
return html.section(
Title("Photo of the day"),
Photo(),
PhotographerName("Steven Spassov")
)
run(PhotoViewer)
The output of the above code is shown below
ReactPy backends
ReactPy supports the following backend implementations.
To install ReactPy with fastapi backend run the following command.
pip install "reactpy[fastapi]"
Conclusion
In conclusion, ReactPy enables us to easily create better user interfaces in Python. You can read about the new programming language Mojo .