2025-05-14 21:42:26 +02:00

93 lines
2.6 KiB
TypeScript

import React, { useRef } from 'react';
import classNames from 'classnames/bind';
import ModuleButton from 'components/items/ModuleButton';
import GenericFields from 'components/formHelpers/GenericFields';
import GenericDropDown from 'components/pageItems/GenericDropDown';
import get from 'lodash/get';
import { FormSpy } from 'react-final-form';
import styleIdentifiers from './genericFieldArray.scss';
const styles = classNames.bind(styleIdentifiers);
export interface StateProps {
infos: Record<string, any>;
}
export interface DispatchProps {}
export interface OwnProps {}
export type GenericFieldArrayProps = StateProps & DispatchProps & OwnProps;
const GenericFieldArray = (props: GenericFieldArrayProps) => {
const { fields, item, formValues, infos, resourceData, finalForm, lg, activeLgs } = props;
function deleteItem(index: number) {
// could add a are you sure
fields.remove(index);
}
function renderTitle(values, name) {
const value = get(values, `${name}.${item?.dropdownLabel || 'title'}`);
if (!value) return false;
return value;
}
function addField() {
fields.push();
}
return (
<div className={styles('GenericFieldArray')}>
{fields &&
fields.map(
(name, index): JSX => (
<FormSpy key={index}>
{({ values }) => (
<GenericDropDown
title={renderTitle(values, name) || `Item ${index + 1}`}
titleClassName={styles('title-dropdown')}
className={styles('list-value')}
>
<GenericFields
formValues={formValues}
push={fields}
fields={infos}
base={name}
activeLgs={activeLgs}
resourceData={resourceData}
finalForm={finalForm}
/>
<div className={styles('buttons')}>
<ModuleButton
small
className={styles('delete')}
relative
color="red"
noMargin
label={item.labelRemove || 'Remove item'}
action={() => deleteItem(index)}
/>
</div>
</GenericDropDown>
)}
</FormSpy>
),
)}
<ModuleButton
action={addField}
label={item.labelAdd || 'Add'}
color="primary"
small
noMargin
relative
/>
</div>
);
};
export default GenericFieldArray;