동적 컴포넌트로 수정하는 과정 기록!
아래처럼 반복적으로 컴포넌트를 가져와야하는 상황에서
컴포넌트 수가 많아짐에 따라 동적으로 처리하는 방법을 고민했다.
(진짜 이러진 않았고 예시!)
import Comp1 from '@/app/components/MainItem/Comp';
import Comp2 from '@/app/components/GridItem/components/Comp';
import Comp3 from '@/app/components/GridItem/components/Comp';
import Comp4 from '@/app/components/GridItem/components/Comp';
import Comp5 from '@/app/components/GridItem/components/Comp';
import Comp6 from '@/app/components/GridItem/components/Comp';
export default function SoManyComps(){
return(
<Comp1 />
<Comp2 />
<Comp3 />
<Comp4 />
<Comp5 />
<Comp6 />
)
}
https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#nextdynamic
Next.js에서는 동적으로 컴포넌트를 가져올 수 있다.
next/dynamic is a composite of React.lazy() and Suspense.
It behaves the same way in the app and pages directories to allow for incremental migration.
커스텀 로딩 예시를 보면 dynamic을 import해서 컴포넌트를 불러내고
그 변수를 컴포넌트로 사용할 수 있다!
템플릿 리터럴을 사용해 동적으로 import src를 수정한다면 컴포넌트가 100개가 되어도 한번에 처리할 수 있겠지 ㅇㅅㅇ!
import dynamic from 'next/dynamic'
const WithCustomLoading = dynamic(
() => import('../components/WithCustomLoading'),
{
loading: () => <p>Loading...</p>,
}
)
export default function Page() {
return (
<div>
{/* The loading component will be rendered while <WithCustomLoading/> is loading */}
<WithCustomLoading />
</div>
)
}
로딩처리도 할 수 있대서 넣어봤다.
"use client"
import data from '@/data/data.json';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/navigation';
return(
<section className={`gridSection ` + filter}>
{
data.map((item)=> {
const DynamicComponent = dynamic(() => import(`./components/${item.keyword}`),
{ loading: () => <div>로딩중입니다!</div> });
return <DynamicComponent key={item.keyword} />
})
}
</section>
)
정상작동 확인 후 커밋!