Skip to content

Commit 50dd498

Browse files
committed
fix(TemplateArrayField): use uncontrolled tabs
1 parent 5f782dc commit 50dd498

File tree

1 file changed

+45
-35
lines changed

1 file changed

+45
-35
lines changed

src/components/TemplateArrayField.tsx

Lines changed: 45 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React from 'react'
1+
import React, { useState } from 'react'
22
import { FrIconClassName, RiIconClassName } from '@codegouvfr/react-dsfr'
33
import Button from '@codegouvfr/react-dsfr/Button'
44
import Tabs from '@codegouvfr/react-dsfr/Tabs'
@@ -30,59 +30,69 @@ export default function ({
3030
items,
3131
canAdd,
3232
onAddClick,
33+
registry,
3334
}: ArrayFieldTemplateProps & { uiSchema?: UiSchemaDSFR }) {
35+
const [selectedTabId, setSelectedTabId] = useState('tab0')
3436
const tabLabel = uiSchema?.['ui:tabLabel'] ?? 'Element'
3537
const removeIcon = uiSchema?.['ui:removeIcon'] ?? 'fr-icon-delete-line'
3638
const addIcon = uiSchema?.['ui:addIcon'] ?? 'fr-icon-add-circle-line'
37-
console.log('items', items)
39+
40+
// ensure no exception when last selected tab has been destroyed
41+
const selectedIndex = Math.min(
42+
items.length - 1,
43+
parseInt(selectedTabId.replace(/^tab(\d+)$/, '$1')),
44+
)
45+
46+
const tabContent =
47+
(items.length && (
48+
<>
49+
<Button
50+
type="button"
51+
iconId={removeIcon}
52+
onClick={(e) => {
53+
items[selectedIndex].onDropIndexClick(selectedIndex)()
54+
}}
55+
size="small"
56+
priority="secondary"
57+
>
58+
Supprimer
59+
</Button>
60+
{items[selectedIndex].children}
61+
</>
62+
)) ||
63+
null
64+
65+
const onTabChange = (id: string) => {
66+
if (id === 'add') {
67+
onAddClick()
68+
setSelectedTabId(`tab${items.length}`)
69+
return
70+
}
71+
setSelectedTabId(id)
72+
}
73+
3874
return (
3975
<div className="form-group field">
4076
<div className="fr-input-group">
4177
<label className="fr-label">{title}</label>
4278
<div className="fr-input-wrap">
4379
<Tabs
80+
onTabChange={onTabChange}
81+
selectedTabId={selectedTabId}
4482
tabs={items
4583
.map((element) => ({
4684
label: `${tabLabel} ${element.index + 1}`,
47-
content: (
48-
<>
49-
<Button
50-
type="button"
51-
iconId={removeIcon}
52-
onClick={(e) => {
53-
console.log('io', element)
54-
element.onDropIndexClick(element.index)
55-
}}
56-
size="small"
57-
priority="secondary"
58-
>
59-
Supprimer
60-
</Button>
61-
{element.children}
62-
</>
63-
),
85+
tabId: `tab${element.index}`,
6486
}))
6587
.concat([
6688
{
6789
label: `Ajouter`,
68-
content: (
69-
<>
70-
{canAdd && (
71-
<Button
72-
type="button"
73-
iconId={addIcon}
74-
onClick={onAddClick}
75-
size="small"
76-
priority="secondary"
77-
>
78-
Ajouter
79-
</Button>
80-
)}
81-
</>
82-
),
90+
tabId: 'add',
8391
},
8492
])}
85-
/>
93+
>
94+
{selectedTabId !== 'add' && tabContent}
95+
</Tabs>
8696
</div>
8797
</div>
8898
</div>

0 commit comments

Comments
 (0)