Skip to content

Commit

Permalink
fix: useIdWithFallback for react 17 and lower (#122)
Browse files Browse the repository at this point in the history
* fix: fix useIdWithFallback for react 17

* fix: use toString() webpack exportPresence workaround

---------

Co-authored-by: Michael David Kuckuk <[email protected]>
  • Loading branch information
jorgeepc and LBBO authored Aug 9, 2023
1 parent 3c06879 commit 31b1208
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions src/common/useIdWithFallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@

import * as React from "react"

const fallback = () => Math.random().toString(36).substring(2)

/**
* A function to obtain a unique ID. If react is available, this
* is just a wrapper for React.useId(), meaning the ID will be
* consistent across SSR and CSR. Otherwise, it will be a random and
* unique ID on every call.
*/
export const useIdWithFallback = () => {
try {
return React.useId()
} catch (e) {
return Math.random().toString(36).substring(2)
}
}
export const useIdWithFallback =
// This weird import circumvents webpack's exportPresence check,
// since we're fine if the import doesn't exist, and we don't want
// it to cause a build error.
React["useId".toString() as "useId"] ?? fallback

0 comments on commit 31b1208

Please sign in to comment.