"Welcome" if you're logged in, "Please log in" if you're not. Apps often need to show different content depending on their state. In this lesson, you'll use rx.cond to change the page based on a State value.
class LoginState(rx.State):
logged_in: bool = False
@rx.event
def toggle_login(self):
self.logged_in = not self.logged_in
def show_login():
return rx.box(
rx.cond(
LoginState.logged_in,
rx.heading("Logged In", as_="h2"),
rx.heading("Not Logged In", as_="h2"),
),
rx.button("Toggle Login", on_click=LoginState.toggle_login),
)localhost:3000
Try itrx.cond takes three arguments.
| Position | Argument | In this example |
|---|---|---|
| 1 | The condition (a Var) | LoginState.logged_in |
| 2 | The component to show when the condition is true | The "Logged In" heading |
| 3 | The component to show when the condition is false | The "Not Logged In" heading |
rx.cond(LoginState.logged_in, rx.text("Welcome!")), the text appears only when you're logged in, and nothing is shown otherwise.toggle_login handler is an ordinary event handler, just like in Lesson 1. It uses not to flip between true and false.In plain Python, you'd be tempted to write this:
def show_login():
if LoginState.logged_in:
return rx.heading("Logged In", as_="h2")
return rx.heading("Not Logged In", as_="h2")This code doesn't work. A UI function runs only once, when the app starts, and at that point there's no way to know whether the user is logged in. rx.cond plants an instruction in the page instead: "check the value later, in the browser, and pick one."
Lesson 4 explains in detail why this happens. For now, just remember: "to branch on a State value in UI code, use rx.cond."
show_login, make the button label change with the state too, switching between "Log In" and "Log Out". Hint: put an rx.cond(...) where the button's child goes.rx.cond works for prop values as well. Make the heading's color "green" when logged in and "gray" otherwise.rx.cond is.if on State values in UI code.← Previous
Lesson 1 · Click and it changes: State and events
Next →
Lesson 3 · Drawing lists: rx.foreach
Get news about new lessons
We'll email you when this course gets new lessons or a follow-up course opens.
R
ReflexKR
Learn Python and Reflex by doing. Every example was run and verified on Reflex 0.10.0.
ReflexKR is free, with no banner ads. If it helped you, you can support it with a coffee. ☕ Buy us a coffee
Affiliate disclosure© 2026 ReflexKR · Since 2026 · CC BY-NC 4.0
Questions & answers
Ask anything about this lesson. Questions from every language version of this page appear together.