page.mdx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. export const metadata = { title: "Data Binding" }
  2. # Data Binding
  3. Connect UI components to your application data using JSON Pointer paths.
  4. ## JSON Pointer Paths
  5. json-render uses JSON Pointer (RFC 6901) for data paths:
  6. ```json
  7. // Given this data:
  8. {
  9. "user": {
  10. "name": "Alice",
  11. "email": "alice@example.com"
  12. },
  13. "metrics": {
  14. "revenue": 125000,
  15. "growth": 0.15
  16. }
  17. }
  18. // These paths access:
  19. "/user/name" -> "Alice"
  20. "/metrics/revenue" -> 125000
  21. "/metrics/growth" -> 0.15
  22. ```
  23. ## StateProvider
  24. Wrap your app with StateProvider to enable data binding:
  25. ```tsx
  26. import { StateProvider } from '@json-render/react';
  27. function App() {
  28. const initialState = {
  29. user: { name: 'Alice' },
  30. form: { email: '', message: '' },
  31. };
  32. return (
  33. <StateProvider initialState={initialState}>
  34. {/* Your UI */}
  35. </StateProvider>
  36. );
  37. }
  38. ```
  39. ## Reading Data
  40. Use `useStateValue` for read-only access:
  41. ```tsx
  42. import { useStateValue } from '@json-render/react';
  43. function UserGreeting() {
  44. const name = useStateValue('/user/name');
  45. return <h1>Hello, {name}!</h1>;
  46. }
  47. ```
  48. ## Two-Way Binding
  49. Use `useStateBinding` for read-write access:
  50. ```tsx
  51. import { useStateBinding } from '@json-render/react';
  52. function EmailInput() {
  53. const [email, setEmail] = useStateBinding('/form/email');
  54. return (
  55. <input
  56. type="email"
  57. value={email || ''}
  58. onChange={(e) => setEmail(e.target.value)}
  59. />
  60. );
  61. }
  62. ```
  63. ## Using the State Context
  64. Access the full state context for advanced use cases:
  65. ```tsx
  66. import { useStateStore } from '@json-render/react';
  67. function StateDebugger() {
  68. const { data, setState, getValue, setValue } = useStateStore();
  69. // Read any path
  70. const revenue = getValue('/metrics/revenue');
  71. // Write any path
  72. const updateRevenue = () => setValue('/metrics/revenue', 150000);
  73. // Replace all state
  74. const resetState = () => setState({ user: {}, form: {} });
  75. return <pre>{JSON.stringify(data, null, 2)}</pre>;
  76. }
  77. ```
  78. ## In JSON UI Trees
  79. AI can reference data paths in component props:
  80. ```json
  81. {
  82. "type": "Metric",
  83. "props": {
  84. "label": "Total Revenue",
  85. "valuePath": "/metrics/revenue",
  86. "format": "currency"
  87. }
  88. }
  89. ```
  90. ## Next
  91. Learn about [actions](/docs/actions) for user interactions.