@kaliber/forms 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaliber/forms",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "main": "index.js",
5
5
  "sideEffects": false,
6
6
  "publishConfig": {
package/readme.md CHANGED
@@ -313,6 +313,40 @@ array(validation, fields)
313
313
  array(fields)
314
314
  ```
315
315
 
316
+ If you want to use heterogeneous arrays (different types) you can use a `function` instead of a `fields` object:
317
+
318
+ ```js
319
+ array(initialValue => ({
320
+ _type: required,
321
+ ...(
322
+ initialValue._type === 'content' ? { text: required } :
323
+ initialValue._type === 'image' ? { image: required } :
324
+ null
325
+ )
326
+ }))
327
+ ```
328
+
329
+ When rendering the `array` field you can render a different component based on the value of the field:
330
+
331
+ ```jsx
332
+ const { state: { children }, helpers } = useArrayFormField(field)
333
+
334
+ return (
335
+ <>
336
+ {children.map(field => {
337
+ const { _type } = field.value.get()
338
+ return (
339
+ _type === 'content' ? <ContentForm key={field.name} {...{ field }} /> :
340
+ _type === 'image' ? <ImageForm key={field.name} {...{ field }} /> :
341
+ null
342
+ )
343
+ })}
344
+ <button type='button' onClick={_ => helpers.add({ _type: 'content' })}>Add content</button>
345
+ <button type='button' onClick={_ => helpers.add({ _type: 'image' })}>Add image</button>
346
+ </>
347
+ )
348
+ ```
349
+
316
350
  #### object
317
351
 
318
352
  Used to create an object form field.
package/src/fields.js CHANGED
@@ -130,10 +130,11 @@ function createArrayFormField({ name, initialValue = [], field }) {
130
130
 
131
131
  function createFormField(initialValue) {
132
132
  const fullName = `${name}[${index++}]`
133
+ const fields = typeof field.fields == 'function' ? field.fields(initialValue) : field.fields
133
134
  return createObjectFormField({
134
135
  name: fullName,
135
136
  initialValue,
136
- field: normalize({ type: 'object', fields: field.fields }, fullName),
137
+ field: normalize({ type: 'object', fields }, fullName),
137
138
  })
138
139
  }
139
140
  }