-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Generate unique ids within each React island
React's useId hook generates unique IDs by incrementing down the component tree. When multiple react roots are on a single page, these IDs can collide. React provides an option, `identifierPrefix` to prefix ids per root. Using preact adapters context solution, increment an ID per component rendered on a request, preventing collisions.
- Loading branch information
Showing
4 changed files
with
52 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
'@astrojs/react': minor | ||
--- | ||
|
||
Prevent ID collisions in React.useId |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
const contexts = new WeakMap(); | ||
|
||
export function getContext(result) { | ||
if (contexts.has(result)) { | ||
return contexts.get(result); | ||
} | ||
let ctx = { | ||
c: 0, | ||
get id() { | ||
return 'r' + this.c.toString(); | ||
}, | ||
}; | ||
contexts.set(result, ctx); | ||
return ctx; | ||
} | ||
|
||
export function incrementId(ctx) { | ||
let id = ctx.id; | ||
ctx.c++; | ||
return id; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters