hooks.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. """Add standard Hooks wrapper for React."""
  2. from typing import Optional, Union
  3. from reflex.utils.imports import ImportVar
  4. from reflex.vars import Var, VarData
  5. def _add_react_import(v: Optional[Var], tags: Union[str, list]):
  6. if v is None:
  7. return
  8. if isinstance(tags, str):
  9. tags = [tags]
  10. v._var_data = VarData( # type: ignore
  11. imports={"react": [ImportVar(tag=tag, install=False) for tag in tags]},
  12. )
  13. def const(name, value) -> Optional[Var]:
  14. """Create a constant Var.
  15. Args:
  16. name: The name of the constant.
  17. value: The value of the constant.
  18. Returns:
  19. The constant Var.
  20. """
  21. if isinstance(name, list):
  22. return Var.create(f"const [{', '.join(name)}] = {value}")
  23. return Var.create(f"const {name} = {value}")
  24. def useCallback(func, deps) -> Optional[Var]:
  25. """Create a useCallback hook with a function and dependencies.
  26. Args:
  27. func: The function to wrap.
  28. deps: The dependencies of the function.
  29. Returns:
  30. The useCallback hook.
  31. """
  32. if deps:
  33. v = Var.create(f"useCallback({func}, {deps})")
  34. else:
  35. v = Var.create(f"useCallback({func})")
  36. _add_react_import(v, "useCallback")
  37. return v
  38. def useContext(context) -> Optional[Var]:
  39. """Create a useContext hook with a context.
  40. Args:
  41. context: The context to use.
  42. Returns:
  43. The useContext hook.
  44. """
  45. v = Var.create(f"useContext({context})")
  46. _add_react_import(v, "useContext")
  47. return v
  48. def useRef(default) -> Optional[Var]:
  49. """Create a useRef hook with a default value.
  50. Args:
  51. default: The default value of the ref.
  52. Returns:
  53. The useRef hook.
  54. """
  55. v = Var.create(f"useRef({default})")
  56. _add_react_import(v, "useRef")
  57. return v
  58. def useState(var_name, default=None) -> Optional[Var]:
  59. """Create a useState hook with a variable name and setter name.
  60. Args:
  61. var_name: The name of the variable.
  62. default: The default value of the variable.
  63. Returns:
  64. A useState hook.
  65. """
  66. setter_name = f"set{var_name.capitalize()}"
  67. v = const([var_name, setter_name], f"useState({default})")
  68. _add_react_import(v, "useState")
  69. return v