How to grab file dynamically?
Answered
Brown bear posted this in #help-forum
Brown bearOP
I wanted to use dynamic imports in nextjs to grab my mdx files depending on my url.
For example if I was at http://somewebsite.com/blog/name-of-article, then I would want to import the file inside of public/blogs/name-of-article/index.mdx. Here's the issue, nextjs doesn't support dynamic imports, so how would I be able to import grab my desired file?
For example if I was at http://somewebsite.com/blog/name-of-article, then I would want to import the file inside of public/blogs/name-of-article/index.mdx. Here's the issue, nextjs doesn't support dynamic imports, so how would I be able to import grab my desired file?
Answered by Ray
this work for me
import fs from "fs/promises";
import path from "path";
import { MDXRemote } from "next-mdx-remote/rsc";
import { Hello } from "../../../../public/blogs/Hello";
const components = { Hello };
export default async function Page({
params,
}: {
params: { filename: string };
}) {
const file = await fs.readFile(
path.join(process.cwd(), "public", "blogs", `${params.filename}.mdx`)
);
return (
<div className="prose">
<MDXRemote source={file.toString()} components={components} />
</div>
);
}10 Replies
@Brown bear I wanted to use dynamic imports in nextjs to grab my mdx files depending on my url.
For example if I was at http://somewebsite.com/blog/name-of-article, then I would want to import the file inside of public/blogs/name-of-article/index.mdx. Here's the issue, nextjs doesn't support dynamic imports, so how would I be able to import grab my desired file?
// blog/[filename]/page.tsx
import fs from "fs/promises";
import path from "path";
export default async function Page({
params,
}: {
params: { filename: string };
}) {
const file = await fs.readFile(
path.join(process.cwd(), "public", "blogs", params.filename)
);
return <></>;
}Brown bearOP
I want to be able to use it like:
<File/>
<File/>
I don't think that'd work
Brown bearOP
Here's what I had in mind before I found out dynamic imports weren't a thing:
const Blog = import(`public/blog/${filename}/index.mdx`);
return (
<Blog />
);this work for me
import fs from "fs/promises";
import path from "path";
import { MDXRemote } from "next-mdx-remote/rsc";
import { Hello } from "../../../../public/blogs/Hello";
const components = { Hello };
export default async function Page({
params,
}: {
params: { filename: string };
}) {
const file = await fs.readFile(
path.join(process.cwd(), "public", "blogs", `${params.filename}.mdx`)
);
return (
<div className="prose">
<MDXRemote source={file.toString()} components={components} />
</div>
);
}Answer
Brown bearOP
Okay, thank you!
does it work for you?
Brown bearOP
I found a different solution that works even better haha!
But I do reallly appreciate your help.
ah ok