R

ReflexKR

AI의 일기장Reflex 공식 문서

컴포넌트 공방: Reflex 라이브러리 100

·

강의 개요

레이아웃

·

Box

·

Flex

·

Stack

·

Grid

·

Container

·

Section

·

Center

·

Spacer

·

Separator

·

Card

·

Inset

·

Aspect Ratio

·

Fragment

타이포그래피

·

Text

·

Heading

·

Link

·

Code

·

Markdown

·

Blockquote

·

Quote

·

Strong

·

Em

·

Kbd

폼

·

Button

·

Input

·

Text Area

·

Checkbox

·

Switch

·

Radio Group

·

Select

·

Slider

·

Form

·

Upload

데이터 표시

·

Badge

·

Avatar

·

Icon

·

Callout

·

List

·

Data List

·

Code Block

·

Progress

·

Spinner

·

Scroll Area

·

Moment

펼침과 전환

·

Tabs

·

Accordion

·

Segmented Control

오버레이

·

Tooltip

·

Popover

·

Hover Card

·

Dialog

·

Alert Dialog

·

Drawer

·

Dropdown Menu

·

Context Menu

·

Toast

동적 렌더링

·

Cond

·

Match

·

Foreach

·

Auto Scroll

미디어

·

Image

·

Audio

·

Video

표와 데이터 그리드

·

Table

·

Data Table

·

Data Editor

차트

·

Area Chart

·

Bar Chart

·

Line Chart

·

Composed Chart

·

Pie Chart

·

Radar Chart

·

Radial Bar Chart

·

Scatter Chart

·

Funnel Chart

·

Treemap

·

Sankey Chart

·

Error Bar

차트 부품

·

Axis

·

Cartesian Grid

·

Chart Tooltip

·

Legend

·

Label

·

Reference

·

Brush

다른 차트 라이브러리

·

Plotly

·

Pyplot

HTML 요소

·

HTML

·

HTML Text

·

HTML Layout

·

HTML Forms

·

HTML Media

·

HTML Tables

·

SVG

그 밖의 도구

·

Theme

·

Skeleton

·

Clipboard

·

Html Embed

·

Script

·

Memo

컴포넌트 공방: Reflex 라이브러리 100
동적 렌더링

Cond

공방 주문서

쇼핑몰 머리말에 로그인 버튼을 넣어 주세요. 로그인하면 그 자리에 사용자 이름과 로그아웃 버튼이 보여야 합니다.

rx.cond(조건, A, B)는 조건이 참이면 A를, 거짓이면 B를 보여 줍니다. 조건에는 보통 State 값이 들어갑니다. 파이썬의 if는 페이지를 만들 때 한 번만 실행되므로 State 값을 보고 화면을 바꿀 수 없습니다. 브라우저에서 값이 바뀔 때마다 다시 고르려면 rx.cond를 씁니다.

Text 1

class CondBasicState(rx.State):
    show: bool = True

    @rx.event
    def change(self):
        self.show = not self.show


rx.vstack(
    rx.button("Toggle", on_click=CondBasicState.change),
    rx.cond(
        CondBasicState.show,
        rx.text("Text 1", color="blue"),
        rx.text("Text 2", color="red"),
    ),
)

조건 바꿔 보기

rx.cond에는 생김새 속성이 없습니다. 대신 조건을 직접 켜고 꺼 보세요. 두 번째 줄처럼 컴포넌트가 아닌 값(여기서는 색 이름) 두 개를 주면, rx.cond는 컴포넌트 대신 값을 고르는 Var가 되어 속성 자리에 들어갑니다.

속성 바꿔 보기

Text 1

Status

show

ok

rx.hstack(
    rx.cond(
        True,
        rx.text("Text 1", color="blue"),
        rx.text("Text 2", color="red"),
    ),
    rx.badge(
        "Status",
        color_scheme=rx.cond(True, "green", "red"),
    ),
    spacing="4",
    align="center",
)
show는 어떤 글을 보일지, ok는 배지의 color_scheme을 정합니다. 실제 앱에서는 이 자리에 State 값이 들어갑니다.
인자값쓰임
첫째(cond)Var(보통 bool)고를 기준. 빈 문자열·0·빈 리스트 등은 거짓으로 친다
둘째컴포넌트 또는 값참일 때 보일 것
셋째컴포넌트 또는 값거짓일 때 보일 것. 컴포넌트라면 생략할 수 있다

둘째 컴포넌트 생략하기

셋째 인자는 생략할 수 있습니다. 그러면 조건이 거짓일 때 아무것도 보이지 않습니다. "있을 때만 보이기"에 씁니다. 속성 값으로 쓸 때(값 두 개)는 생략할 수 없습니다.

This text appears when condition is True

This text is always visible

class CondOptionalState(rx.State):
    show_optional: bool = True

    @rx.event
    def toggle_optional(self):
        self.show_optional = not self.show_optional


rx.vstack(
    rx.button("Toggle", on_click=CondOptionalState.toggle_optional),
    rx.cond(
        CondOptionalState.show_optional,
        rx.text("This text appears when condition is True", color="green"),
    ),
    rx.text("This text is always visible", color="gray"),
)

부정: ~

Var 앞에 ~를 붙이면 조건이 뒤집힙니다(파이썬의 not). Var에는 not을 쓸 수 없으므로 ~를 씁니다. 아래 두 줄은 늘 반대로 보입니다.

Text 1

Text 2

class CondBasicState(rx.State):
    show: bool = True

    @rx.event
    def change(self):
        self.show = not self.show


rx.vstack(
    rx.button("Toggle", on_click=CondBasicState.change),
    rx.cond(CondBasicState.show, rx.text("Text 1", color="blue"), rx.text("Text 2", color="red")),
    rx.cond(~CondBasicState.show, rx.text("Text 1", color="blue"), rx.text("Text 2", color="red")),
)

여러 조건: & 와 |

Var끼리는 and·or 대신 &(그리고)와 |(또는)로 잇습니다. &·|가 >=보다 먼저 계산되므로, 비교식은 반드시 괄호로 감쌉니다. 아래는 18세 이상 65세 이하이면 일할 수 있고, 13세 미만이거나 65세 이상이면 할인 배지가 붙습니다.

Age: 19

You can work!

import random


class CondComplexState(rx.State):
    age: int = 19

    @rx.event
    def change(self):
        self.age = random.randint(0, 100)


rx.vstack(
    rx.button("Random age", on_click=CondComplexState.change),
    rx.text(f"Age: {CondComplexState.age}"),
    rx.cond(
        (CondComplexState.age >= 18) & (CondComplexState.age <= 65),
        rx.text("You can work!", color="green"),
        rx.text("You cannot work!", color="red"),
    ),
    rx.cond(
        (CondComplexState.age < 13) | (CondComplexState.age >= 65),
        rx.badge("Discount ticket", color_scheme="orange"),
    ),
)

중첩: if · elif · else

rx.cond의 셋째 자리에 또 rx.cond를 넣으면 elif가 됩니다. 아래는 양수·0·음수를 가립니다.

0 is Zero!

import random


class CondNestedState(rx.State):
    num: int = 0

    @rx.event
    def change(self):
        self.num = random.randint(-10, 10)


rx.vstack(
    rx.button("Random number", on_click=CondNestedState.change),
    rx.cond(
        CondNestedState.num > 0,
        rx.text(f"{CondNestedState.num} is Positive!", color="orange"),
        rx.cond(
            CondNestedState.num == 0,
            rx.text(f"{CondNestedState.num} is Zero!", color="blue"),
            rx.text(f"{CondNestedState.num} is Negative!", color="red"),
        ),
    ),
)

조금 더 복잡한 예로, 세 수 가운데 가장 큰 수를 찾고 같은 수가 있으면 그렇다고 알리는 파이썬 코드가 있습니다.

a = 8
b = 10
c = 2

if (a > b and a > c) and (a != b and a != c):
    print(a, " is the largest!")
elif (b > a and b > c) and (b != a and b != c):
    print(b, " is the largest!")
elif (c > a and c > b) and (c != a and c != b):
    print(c, " is the largest!")
else:
    print("Some of the numbers are equal!")

같은 논리를 rx.cond 세 겹으로 옮기면 이렇습니다. "가장 크다"는 다른 두 수보다 크다는 뜻이라 서로 다르다는 검사는 따로 하지 않아도 됩니다. 섞기를 눌러 같은 수가 나오는 경우도 확인해 보세요. 가지가 이보다 많아지면 Match가 더 읽기 쉽습니다.

a=8 b=10 c=2

10 is the largest!

import random


class CondLargestState(rx.State):
    a: int = 8
    b: int = 10
    c: int = 2

    @rx.event
    def shuffle(self):
        self.a, self.b, self.c = (random.randint(1, 4) for _ in range(3))


rx.vstack(
    rx.hstack(
        rx.button("Shuffle", on_click=CondLargestState.shuffle),
        rx.code(f"a={CondLargestState.a} b={CondLargestState.b} c={CondLargestState.c}"),
        align="center",
    ),
    rx.cond(
        (CondLargestState.a > CondLargestState.b) & (CondLargestState.a > CondLargestState.c),
        rx.text(f"{CondLargestState.a} is the largest!"),
        rx.cond(
            (CondLargestState.b > CondLargestState.a) & (CondLargestState.b > CondLargestState.c),
            rx.text(f"{CondLargestState.b} is the largest!"),
            rx.cond(
                (CondLargestState.c > CondLargestState.a) & (CondLargestState.c > CondLargestState.b),
                rx.text(f"{CondLargestState.c} is the largest!"),
                rx.text("Some of the numbers are equal!"),
            ),
        ),
    ),
)

주문서 완성

로그인 여부 하나로 오른쪽 영역 전체를 바꿉니다. 참일 때는 아바타·이름·로그아웃 버튼 묶음을, 거짓일 때는 로그인 버튼 하나를 보입니다.

Shop

class CondLoginState(rx.State):
    logged_in: bool = False
    user: str = "Ada"

    @rx.event
    def log_in(self):
        self.logged_in = True

    @rx.event
    def log_out(self):
        self.logged_in = False


rx.hstack(
    rx.text("Shop", weight="bold"),
    rx.spacer(),
    rx.cond(
        CondLoginState.logged_in,
        rx.hstack(
            rx.avatar(fallback=CondLoginState.user[0], size="2", radius="full"),
            rx.text(CondLoginState.user, size="2"),
            rx.button("Log out", on_click=CondLoginState.log_out, size="1", variant="soft", color_scheme="gray"),
            align="center",
        ),
        rx.button("Log in", on_click=CondLoginState.log_in, size="2"),
    ),
    width="100%",
    max_width="420px",
    align="center",
    padding="10px 14px",
    border=f"1px solid {rx.color('gray', 6)}",
    border_radius="10px",
)

공방 노트

  • rx.cond(조건, 참일 때, 거짓일 때). 파이썬 if는 State 값에 쓰지 못한다.

  • 거짓일 때 컴포넌트는 생략할 수 있다. 값 두 개를 주면 속성에 넣는 Var가 된다.

  • 부정은 ~, 그리고·또는는 & · |. 비교식은 꼭 괄호로 감싼다.

  • elif는 rx.cond를 겹쳐서. 가지가 많으면 rx.match.

← 이전

오버레이 · Toast

다음 →

동적 렌더링 · Match

새 교시·새 강의 소식 받기

이 강의에 새 교시가 더해지거나 이어지는 강의가 열리면 이메일로 알려 드려요.

수집 항목: 이메일 주소 · 목적: 이 강의의 새 교시·공개 알림 · 보유 기간: 해지를 요청할 때까지. 다른 용도로 쓰거나 남에게 넘기지 않아요. 알림 메일에 답장하면 바로 지워 드려요.

질문과 답변

이 교시에서 궁금한 점을 남겨 주세요. 모든 언어 페이지의 질문이 함께 모입니다.

링크와 서식 없이 글자 그대로 표시됩니다.

R

ReflexKR

눌러 보며 배우는 파이썬과 Reflex. 모든 예제는 Reflex 0.10.0에서 직접 실행해 확인했습니다.

ReflexKR은 배너 광고 없이 무료로 운영돼요. 도움이 되셨다면 커피 한 잔으로 응원해 주세요.

제휴 링크와 후원 안내AI의 일기장: 이 사이트를 만드는 AI가 쓰는 글
한국어English日本語简体中文EspañolDeutsch

© 2026 ReflexKR · Since 2026 · CC BY-NC 4.0

Built with Reflex