diff --git a/lib/RepeatableField/RepeatableField.js b/lib/RepeatableField/RepeatableField.js index ccbae5f03..f8dd47205 100644 --- a/lib/RepeatableField/RepeatableField.js +++ b/lib/RepeatableField/RepeatableField.js @@ -1,4 +1,4 @@ -import React, { useRef, useEffect } from 'react'; +import React, { useRef, useEffect, useState } from 'react'; import classnames from 'classnames'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; @@ -10,8 +10,6 @@ import EmptyMessage from '../EmptyMessage'; import IconButton from '../IconButton'; import { RepeatableFieldContent } from './RepeatableFieldContent'; import css from './RepeatableField.css'; -import { useFocusedIndex } from './hooks/useFocusedIndex'; -import { useIsElementFocused } from './hooks/useIsElementFocused'; import { getFirstFocusable } from '../../util/getFocusableElements'; const RepeatableField = ({ @@ -33,8 +31,7 @@ const RepeatableField = ({ const rootRef = useRef(null); const showDeleteBtn = typeof onRemove === 'function'; const fieldsLength = fields.length; - const isSomeChildElementFocused = useIsElementFocused(rootRef); - const focusedIndex = useFocusedIndex(fieldsLength); + const [hasBeenFocused, setHasBeenFocused] = useState(false); // use mutation observers to handle focus-management since we only have internal state. useEffect(() => { @@ -46,8 +43,12 @@ const RepeatableField = ({ const removedNode = mutation.removedNodes?.[0]; let rowElem; // Handle added node - if (rootRef.current.matches(':focus-within')) { - if (addedNode && addedNode.matches(`.${css.repeatableFieldItem}`)) { + // we check if the user has interacted with the component before handling this, otherwise focus could be + // unwantedly moved when a form is initialized. + if (hasBeenFocused) { + if (addedNode && + addedNode.nodeType === 1 && + addedNode.matches(`.${css.repeatableFieldItem}`)) { rowElem = getFirstFocusable(addedNode); rowElem?.focus(); } @@ -74,9 +75,7 @@ const RepeatableField = ({ return () => { observer.disconnect(); }; - }, []) - - const hasToBeFocused = (index) => isSomeChildElementFocused && focusedIndex === index; + }, [hasBeenFocused]) return (