Py.Cafe

stichbury/

vizro-custom-carousel-component

Custom Carousel Component with Vizro

DocsPricing
  • assets/
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from typing import List, Literal

import dash_bootstrap_components as dbc
import vizro.models as vm
from dash import html
from vizro import Vizro

try:
    from pydantic.v1 import Field, PrivateAttr
except ImportError:
    from pydantic import PrivateAttr

from vizro.models import Action
from vizro.models._action._actions_chain import _action_validator_factory
from vizro.models.types import capture


# 1. Create new custom component
class Carousel(vm.VizroBaseModel):
    type: Literal["carousel"] = "carousel"
    items: List
    actions: List[Action] = []
    # Here we set the action so a change in the active_index property of the custom component triggers the action
    _set_actions = _action_validator_factory("active_index")  

    def build(self):
        return dbc.Carousel(
            id=self.id,
            items=self.items,
        )


# 2. Add new components to expected type - here the selector of the parent components
vm.Page.add_type("components", Carousel)

# 3. Create custom action
@capture("action")
def slide_next_card(active_index):
    if active_index:
        return "Second slide"

    return "First slide"

page = vm.Page(
    title="Custom Component",
    components=[
        vm.Card(text="First slide", id="carousel-card"),
        Carousel(
            id="carousel",
            items=[
                {"key": "1", "src": "assets/slide_1.jpg"},
                {"key": "2", "src": "assets/slide_2.jpg"},
            ],
            actions=[
                vm.Action(
                    function=slide_next_card(),
                    inputs=["carousel.active_index"],
                    outputs=["carousel-card.children"]
                )
            ]
        ),
    ],
)

dashboard = vm.Dashboard(pages=[page])

Vizro().build(dashboard).run()