Skip to content

Commit

Permalink
fix: window is not defined error while using Next.js
Browse files Browse the repository at this point in the history
fix #28
  • Loading branch information
awran5 committed Oct 11, 2022
1 parent 861a357 commit aeeeb57
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions src/Components/Rating.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,18 @@ export interface RatingProps extends StarIconProps {
titleSeparator?: string
}

/**
* Check for touch devices
* @returns `boolean`
*/
function isTouchDevice() {
return (
(typeof window !== 'undefined' && window.matchMedia('(pointer: coarse)').matches) ||
'ontouchstart' in window ||
(typeof navigator !== 'undefined' && navigator.maxTouchPoints > 0)
)
}

export function Rating({
onClick,
onPointerMove,
Expand Down Expand Up @@ -130,11 +142,6 @@ export function Rating({
hoverValue: null
})

/**
* Check for touch devices
* @returns `boolean`
*/
const isTouchDevice = useMemo(() => !!window?.ontouchstart || (typeof navigator !== 'undefined' && navigator.maxTouchPoints > 0), [])
const totalIcons = useMemo(() => (allowFraction ? iconsCount * 2 : iconsCount), [allowFraction, iconsCount])

// Convert local rating value to precentage
Expand Down Expand Up @@ -193,7 +200,7 @@ export function Rating({
const handlePointerEnter = (event: PointerEvent<HTMLSpanElement>) => {
if (onPointerEnter) onPointerEnter(event)
// Enable only on touch devices
if (!isTouchDevice) return
if (!isTouchDevice()) return

handlePointerMove(event)
}
Expand All @@ -206,7 +213,7 @@ export function Rating({
}

const handlePointerLeave = (event: PointerEvent<HTMLSpanElement>) => {
if (isTouchDevice) handleClick()
if (isTouchDevice()) handleClick()

dispatch({ type: 'PointerLeave' })
if (onPointerLeave) onPointerLeave(event)
Expand Down

0 comments on commit aeeeb57

Please sign in to comment.