From 1d218c096cc77cc70bd93f4f11166102317a6392 Mon Sep 17 00:00:00 2001 From: Sven van de Scheur Date: Tue, 6 Jun 2023 15:44:41 +0200 Subject: [PATCH] :recycle: #43 - Use Formik FieldArray. --- .../multiple/multiple.container.tsx | 113 ++++++++---------- 1 file changed, 51 insertions(+), 62 deletions(-) diff --git a/src/containers/multiple/multiple.container.tsx b/src/containers/multiple/multiple.container.tsx index 1b722d6..bbacb79 100644 --- a/src/containers/multiple/multiple.container.tsx +++ b/src/containers/multiple/multiple.container.tsx @@ -1,10 +1,12 @@ import {Component, Description, Label} from '@components'; import {IRenderable, RenderComponent} from '@lib/renderer'; -import {IComponentProps, Values} from '@types'; +import {IComponentProps, Value, Values} from '@types'; +import {ArrayHelpers, FieldArray} from 'formik'; import {ComponentSchema} from 'formiojs'; -import React, {useState} from 'react'; +import React from 'react'; export interface IMultipleComponent extends ComponentSchema { + key: string; type: string; } @@ -20,75 +22,62 @@ export interface IMultipleProps extends IComponentProps { * to render individual instances. */ export const Multiple: React.FC = props => { - const {component, form, path, value = [], setValue} = props; // FIXME: Awaits future pr. - const [keys, setKeys] = useState([0]); - - /** Finds next key by increasing the max key with 1. */ - const getKey = (): number => { - if (!keys.length) { - return 0; - } - const max = Math.max(...keys); - return max + 1; - }; - - /** Add item. */ - const add = () => { - setKeys([...keys, getKey()]); - }; - - /** Remove item at index. */ - const remove = (index: number) => { - const _keys = keys.filter((_, i) => i !== index); - const val = value.filter((_, i) => i !== index); - setKeys(_keys); - setValue(path, val); - }; + const {component, form, path, value = []} = props; // FIXME: Awaits future pr. /** Renders individual components utilizing . */ - const renderComponents = () => - keys.map((key, index) => { - // Clone and adjust component to fit nested needs. - const renderable: IRenderable = { - ...structuredClone(component), - key: `${path}.${index}`, // Trigger Formik array values. - multiple: false, // Handled by - description: '', // One description rendered for all components. - label: '', // One label rendered for all components. - }; + const renderComponent = (value: Value, index: number, remove: ArrayHelpers['remove']) => { + // Clone and adjust component to fit nested needs. + const renderable: IRenderable = { + ...structuredClone(component), + key: `${path}.${index}`, // Trigger Formik array values. + multiple: false, // Handled by + description: '', // One description rendered for all components. + label: '', // One label rendered for all components. + }; - return ( - - - - - - - - - ); - }); + return ( + + + + + + + + + ); + }; return ( {props.component.label && ( );