propcond.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """Create a Prop Condition."""
  2. from typing import Any
  3. from pynecone import utils
  4. from pynecone.base import Base
  5. from pynecone.var import Var
  6. class PropCond(Base):
  7. """A conditional prop."""
  8. # The condition to determine which prop to render.
  9. cond: Var[Any]
  10. # The prop to render if the condition is true.
  11. prop1: Any
  12. # The prop to render if the condition is false.
  13. prop2: Any
  14. @classmethod
  15. def create(cls, cond: Var, prop1: Any, prop2: Any = None):
  16. """Create a conditional Prop.
  17. Args:
  18. cond: The cond to determine which prop to render.
  19. prop1: The prop value to render if the cond is true.
  20. prop2: The prop value to render if the cond is false.
  21. Returns:
  22. The conditional Prop.
  23. """
  24. return cls(
  25. cond=cond,
  26. prop1=prop1,
  27. prop2=prop2,
  28. )
  29. def __str__(self) -> str:
  30. """Render the prop as a React string.
  31. Returns:
  32. The React code to render the prop.
  33. """
  34. assert self.cond is not None, "The condition must be set."
  35. return utils.format_cond(
  36. cond=self.cond.full_name,
  37. true_value=self.prop1,
  38. false_value=self.prop2,
  39. is_prop=True,
  40. )