diff --git a/packages/dnb-eufemia/src/extensions/forms/hooks/__tests__/usePath.test.tsx b/packages/dnb-eufemia/src/extensions/forms/hooks/__tests__/usePath.test.tsx
index 05d54e66d9b..010419eb012 100644
--- a/packages/dnb-eufemia/src/extensions/forms/hooks/__tests__/usePath.test.tsx
+++ b/packages/dnb-eufemia/src/extensions/forms/hooks/__tests__/usePath.test.tsx
@@ -70,6 +70,24 @@ describe('usePath', () => {
)
})
+ it('should clean paths properly when "iteratePath" is just a slash', () => {
+ const path = '/path'
+ const iteratePath = '/'
+ const itemPath = '/itemPath'
+ const iterateElementIndex = 0
+ const { result } = renderHook(() => usePath({ path, itemPath }), {
+ wrapper: ({ children }) => (
+
+ {children}
+
+ ),
+ })
+ expect(result.current.path).toBe(`/${iterateElementIndex}${itemPath}`)
+ expect(result.current.itemPath).toBe(
+ `/${iterateElementIndex}${itemPath}`
+ )
+ })
+
it('should return a combined path when Iterate is inside Form.Section', () => {
const path = '/path'
const sectionPath = '/sectionPath'
diff --git a/packages/dnb-eufemia/src/extensions/forms/hooks/usePath.ts b/packages/dnb-eufemia/src/extensions/forms/hooks/usePath.ts
index 24f1406272b..c9f32f2566c 100644
--- a/packages/dnb-eufemia/src/extensions/forms/hooks/usePath.ts
+++ b/packages/dnb-eufemia/src/extensions/forms/hooks/usePath.ts
@@ -25,17 +25,16 @@ export default function usePath(props: Props = {}) {
}
const joinPath = useCallback((paths: Array) => {
- return paths
- .reduce((acc, cur) => (cur ? `${acc}/${cur}` : acc), '/')
- .replace(/\/{2,}/g, '/')
- .replace(/\/+$/, '')
+ return cleanPath(
+ paths.reduce((acc, cur) => (cur ? `${acc}/${cur}` : acc), '/')
+ )
}, [])
const makeSectionPath = useCallback(
(path: Path) => {
- return `${
- sectionPath && sectionPath !== '/' ? sectionPath : ''
- }${path}`.replace(/\/$/, '')
+ return cleanPath(
+ `${sectionPath && sectionPath !== '/' ? sectionPath : ''}${path}`
+ )
},
[sectionPath]
)
@@ -51,15 +50,17 @@ export default function usePath(props: Props = {}) {
root = makeSectionPath('')
}
- return `${root}${iteratePath || ''}/${iterateElementIndex}${
- itemPath && itemPath !== '/' ? itemPath : ''
- }`
+ return cleanPath(
+ `${root}${iteratePath || ''}/${iterateElementIndex}${
+ itemPath || ''
+ }`
+ )
},
[
+ itemPathProp,
iteratePathProp,
sectionPath,
iterateElementIndex,
- itemPathProp,
makeSectionPath,
]
)
@@ -101,3 +102,9 @@ export default function usePath(props: Props = {}) {
makeSectionPath,
}
}
+
+// Will remove duplicate slashes and trailing slashes
+// /foo///bar/// => /foo/bar
+function cleanPath(path: Path) {
+ return path.replace(/\/+$|\/(\/)+/g, '$1')
+}