Skip to content

Commit 70de072

Browse files
committed
feat: enhance PhoneInput component with mounted state for dropdown rendering
- Introduced a mounted state to manage the rendering of the dropdown container. - Updated event listener cleanup to depend on the mounted state. - Refactored dropdown rendering logic to use the portal container based on the mounted state.
1 parent 7aa3e2a commit 70de072

1 file changed

Lines changed: 12 additions & 3 deletions

File tree

packages/survey-ui/src/components/general/phone-input.tsx

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ function PhoneInput({
3939
}: Readonly<PhoneInputProps>): React.JSX.Element {
4040
const [isOpen, setIsOpen] = React.useState(false);
4141
const [search, setSearch] = React.useState("");
42+
const [mounted, setMounted] = React.useState(false);
4243
const [dropdownPosition, setDropdownPosition] = React.useState<{
4344
top: number;
4445
left: number;
@@ -48,6 +49,10 @@ function PhoneInput({
4849
const dropdownRef = React.useRef<HTMLDivElement>(null);
4950
const searchInputRef = React.useRef<HTMLInputElement>(null);
5051

52+
React.useEffect(() => {
53+
setMounted(true);
54+
}, []);
55+
5156
const parseValue = React.useCallback((): { country: Country; phoneNumber: string } => {
5257
if (!value) {
5358
return { country: getDefaultCountry(), phoneNumber: "" };
@@ -122,6 +127,8 @@ function PhoneInput({
122127
}, [isOpen]);
123128

124129
React.useEffect(() => {
130+
if (!mounted) return;
131+
125132
const handleClickOutside = (event: MouseEvent): void => {
126133
const target = event.target as Node;
127134
if (
@@ -145,10 +152,12 @@ function PhoneInput({
145152
return () => {
146153
document.removeEventListener("mousedown", handleClickOutside);
147154
};
148-
}, [isOpen]);
155+
}, [isOpen, mounted]);
149156

150157
const hasError = Boolean(errorMessage);
151158

159+
const portalContainer = mounted && typeof document !== "undefined" ? document.body : null;
160+
152161
return (
153162
<div className="space-y-1">
154163
<ElementError errorMessage={errorMessage} dir={dir} />
@@ -199,7 +208,7 @@ function PhoneInput({
199208
</button>
200209
</div>
201210

202-
{isOpen && dropdownPosition && typeof document !== "undefined"
211+
{isOpen && dropdownPosition && portalContainer
203212
? createPortal(
204213
<div
205214
ref={dropdownRef}
@@ -262,7 +271,7 @@ function PhoneInput({
262271
)}
263272
</div>
264273
</div>,
265-
document.body
274+
portalContainer
266275
)
267276
: null}
268277

0 commit comments

Comments
 (0)