@react-jsonr/plugin-event-handlers
Version:
Event handler mapping plugin for React-JSONR
94 lines (74 loc) • 2.31 kB
Markdown
for React-JSONR that maps string event handler references to actual functions.
```bash
npm install @react-jsonr/plugin-event-handlers
yarn add @react-jsonr/plugin-event-handlers
pnpm add @react-jsonr/plugin-event-handlers
```
```tsx
import React from 'react';
import { renderNode, transformJsonTree, createRegistry } from 'react-jsonr';
import { createEventHandlerPlugin } from '@react-jsonr/plugin-event-handlers';
// Define your event handlers
const eventHandlers = {
submitForm: () => {
alert('Form submitted!');
},
handleChange: (e) => {
console.log('Input changed:', e.target.value);
}
};
// Create the event handler plugin
const eventHandlerPlugin = createEventHandlerPlugin({
handlers: eventHandlers
});
// Define your UI as JSON
const jsonDefinition = {
type: 'Form',
props: {
onSubmit: 'submitForm' // This will be mapped to the actual function
},
children: [
{
type: 'Input',
props: {
type: 'text',
onChange: 'handleChange' // This will be mapped to the actual function
}
}
]
};
// Transform the JSON tree with the plugin
const transformed = await transformJsonTree(jsonDefinition, [eventHandlerPlugin]);
// Create a component registry
const registry = createRegistry({
Form: ({ children, ...props }) => (
<form {...props}>{children}</form>
),
Input: (props) => <input {...props} />
});
// Render the component
const element = renderNode(transformed, registry);
```
The `createEventHandlerPlugin` function accepts an options object with the following properties:
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `handlers` | `Record<string, Function>` | (required) | Map of event handler names to functions |
| `prefix` | `string` | `'on'` | Custom prefix for event handler props |
| `warnOnMissing` | `boolean` | `true` | Whether to warn when an event handler is not found |
```tsx
const eventHandlerPlugin = createEventHandlerPlugin({
handlers: eventHandlers,
prefix: 'handle', // Will only transform props starting with 'handle'
warnOnMissing: false // Silently ignore missing event handlers
});
```
MIT
A plugin