Skip to content

Commit 5c92fe4

Browse files
authored
Merge pull request #643 from error9098x/mathrandom
fix(upload-widget): replace random script id with stable useId-based id
2 parents 5662382 + 966198c commit 5c92fe4

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

next-cloudinary/src/components/CldUploadWidget/CldUploadWidget.tsx

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,19 @@ import {
2323

2424
import { getCloudinaryConfig } from "../../lib/cloudinary";
2525

26+
// Stable ID hook with React 18+ useId and React < 18 fallback
27+
const useUploadWidgetId = (): string => {
28+
const reactId = (React as { useId?: () => string }).useId?.() ?? null;
29+
30+
// Preserve the original random ID behavior for React < 18
31+
const fallbackId = React.useRef(Math.floor(Math.random() * 100)).current;
32+
33+
// Remove colons from React useId() output (e.g., ":r1:" -> "r1") to avoid issues with CSS selectors and HTML IDs
34+
const sanitizedId = reactId ? reactId.replace(/:/g, '') : fallbackId;
35+
36+
return `cloudinary-uploadwidget-${sanitizedId}`;
37+
};
38+
2639
const CldUploadWidget = ({
2740
children,
2841
config,
@@ -34,6 +47,7 @@ const CldUploadWidget = ({
3447
uploadPreset,
3548
...props
3649
}: CldUploadWidgetProps) => {
50+
const uploadWidgetId = useUploadWidgetId();
3751
const cloudinary: CldUploadWidgetCloudinaryInstance = useRef();
3852
const widget: CldUploadWidgetWidgetInstance = useRef();
3953

@@ -239,7 +253,7 @@ const CldUploadWidget = ({
239253
...instanceMethods,
240254
})}
241255
<Script
242-
id={`cloudinary-uploadwidget-${Math.floor(Math.random() * 100)}`}
256+
id={uploadWidgetId}
243257
src="https://upload-widget.cloudinary.com/global/all.js"
244258
onLoad={handleOnLoad}
245259
onError={(e) => console.error(`Failed to load Cloudinary Upload Widget: ${e.message}`)}

0 commit comments

Comments
 (0)