link.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """A link component."""
  2. from __future__ import annotations
  3. from reflex.components.chakra import ChakraComponent
  4. from reflex.components.component import Component
  5. from reflex.components.next.link import NextLink
  6. from reflex.utils import imports
  7. from reflex.vars import BaseVar, Var
  8. next_link = NextLink.create()
  9. class Link(ChakraComponent):
  10. """Link to another page."""
  11. tag = "Link"
  12. # The rel.
  13. rel: Var[str]
  14. # The page to link to.
  15. href: Var[str]
  16. # The text to display.
  17. text: Var[str]
  18. # What the link renders to.
  19. as_: Var[str] = BaseVar.create(value="{NextLink}", _var_is_local=False) # type: ignore
  20. # If true, the link will open in new tab.
  21. is_external: Var[bool]
  22. def _get_imports_list(self) -> list[imports.ImportVar]:
  23. return [*super()._get_imports_list(), *next_link._get_imports_list()]
  24. @classmethod
  25. def create(cls, *children, **props) -> Component:
  26. """Create a Link component.
  27. Args:
  28. *children: The children of the component.
  29. **props: The props of the component.
  30. Raises:
  31. ValueError: in case of missing children
  32. Returns:
  33. Component: The link component
  34. """
  35. if props.get("href") is not None:
  36. if not len(children):
  37. raise ValueError("Link without a child will not display")
  38. else:
  39. # Don't use a NextLink if there is no href.
  40. props["as_"] = ""
  41. return super().create(*children, **props)