link.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """A link component."""
  2. from typing import Optional
  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: Optional[Var[str]] = None
  14. # The page to link to.
  15. href: Optional[Var[str]] = None
  16. # The text to display.
  17. text: Optional[Var[str]] = None
  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: Optional[Var[bool]] = None
  22. def _get_imports(self) -> imports.ImportDict:
  23. return {**super()._get_imports(), **next_link._get_imports()}
  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)