Skip to content

Commit

Permalink
Merge pull request #17 from yun-cheng/feat/image-lazy-loading
Browse files Browse the repository at this point in the history
feat(ResultsPage): large image lazy loading
  • Loading branch information
yun-cheng authored Mar 23, 2024
2 parents 4ea1bfa + da57f53 commit ece084d
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 3 deletions.
38 changes: 38 additions & 0 deletions src/components/common/LazyImage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { ComponentProps, ReactElement } from 'react'
import { useInView } from 'react-intersection-observer'
import cn from 'utils/cn'

type Props = ComponentProps<'img'> & {
rootSelector?: string
rootMargin?: string
}

export default function LazyImage({
src,
alt,
rootSelector = undefined,
rootMargin = '250px 0px',
className,
...props
}: Props): ReactElement {
const { ref, inView } = useInView({
root: rootSelector ? document.querySelector(rootSelector) : undefined,
triggerOnce: true,
rootMargin
})

return (
<div ref={ref} className={cn('relative', className)}>
<div className='absolute inset-0 -z-10 w-full bg-[#363636]' />
{!!inView && (
<img
className='h-full w-full'
src={src}
alt={alt}
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
/>
)}
</div>
)
}
8 changes: 7 additions & 1 deletion src/components/result/ResultItem.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import LazyImage from 'components/common/LazyImage'
import type { ReactElement } from 'react'
import type { Result } from 'types/result'
import cn from 'utils/cn'
Expand All @@ -11,7 +12,12 @@ export default function ResultItem({
}: Props): ReactElement {
return (
<div>
<img className='aspect-[1.5] w-full' src={avater} alt='avatar' />
<LazyImage
className='aspect-[1.5] w-full'
rootSelector='#resultsContainer'
src={avater}
alt='avatar'
/>
<div
className={cn(
'mt-[20.33px] sm:mt-3',
Expand Down
8 changes: 6 additions & 2 deletions src/pages/ResultsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default function ResultsPage(): ReactElement {

const { ref, inView } = useInView({
root: containerRef.current,
rootMargin: '0px 0px 250px'
rootMargin: '250px 0px'
})

const { data, isFetching, fetchNextPage } = useFetchResults()
Expand All @@ -25,7 +25,11 @@ export default function ResultsPage(): ReactElement {

return (
<div className={cn('h-screen px-[7px] sm:px-[14px]', 'flex flex-col')}>
<div ref={containerRef} className='mt-[70px] overflow-y-auto sm:mt-0'>
<div
id='resultsContainer'
ref={containerRef}
className='mt-[70px] overflow-y-auto sm:mt-0'
>
<div className='mx-auto max-w-[814px]'>
<div
className={cn(
Expand Down

0 comments on commit ece084d

Please sign in to comment.