Skip to content

Decorators

Overview

Decorator functions can be used within your components.py to help simplify development.


User Passes Test

You can limit component access to users that pass a test function by using this decorator.

This only works with ReactPy components, and is inspired by Django's user_passes_test decorator.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from reactpy import component, html

from reactpy_django.decorators import user_passes_test


def is_authenticated(user):
    return user.is_authenticated


@user_passes_test(is_authenticated)
@component
def my_component():
    return html.div("I am logged in!")
See Interface

Parameters

Name Type Description Default
test_func Callable[[AbstractUser], bool] A function that accepts a User returns a boolean. N/A
fallback Any | None The content to be rendered if the test fails. Typically is a ReactPy component or VDOM (reactpy.html snippet).

Returns

Type Description
ComponentConstructor A ReactPy component constructor.
How do I render a different component if the test fails?

You can use a component with the fallback argument, as seen below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from reactpy import component, html

from reactpy_django.decorators import user_passes_test


@component
def my_component_fallback():
    return html.div("I am NOT logged in!")


def is_authenticated(user):
    return user.is_authenticated


@user_passes_test(is_authenticated, fallback=my_component_fallback)
@component
def my_component():
    return html.div("I am logged in!")
How do I render a simple reactpy.html snippet if the test fails?

You can use a reactpy.html snippet with the fallback argument, as seen below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from reactpy import component, html

from reactpy_django.decorators import user_passes_test


def is_authenticated(user):
    return user.is_authenticated


@user_passes_test(is_authenticated, fallback=html.div("I am NOT logged in!"))
@component
def my_component():
    return html.div("I am logged in!")

Last update: December 2, 2024
Authors: Mark Bakhit