Next.js Discord

Discord Forum

dynamic import a component not working

Unanswered
Somali posted this in #help-forum
Open in Discord
SomaliOP
i think i've tried every example i found on google, but non of them work. my current setup:

function getDynamicComponent(c: any) {
    const newPath = `../previews/${c}Preview`;
    return dynamic(() => import(''+newPath), {
        ssr: false,
        loading: () => <p>Loading...</p>,
    })
}

const PostLayout = ({ params }: { params: { slug: string } }) => {
    const [PreviewComponent, setPreviewComponent] = useState<any>(null);

    // i define post.title somewhere here
    const previewComponentTitle = post.title + "Preview"
    console.log(previewComponentTitle)
    const DynamicComponent = getDynamicComponent(post.title)

    return (
        <article className="py-8 w-full">
            <div className="mb-8 text-center">
                <h1 className="text-3xl font-bold">{post.title}</h1>
            </div>
            <DynamicComponent />
        </article>
    )
}

export default PostLayout


it's saying "Cannot find module '../previews/ParticleSea
Preview'"

when i manually copy that path, and set it as the import path directly, it works
any help? been stuck on this for quite some time

0 Replies