Passing variables to use inside MDX file
See original GitHub issueHi, I’m using gatsby-plugin-mdx to add rich markdown to my site.
I want to access the frontmatter of the markdown within the markdown itself.
The docs say this is available in my MDX file with {props.pageContext.frontmatter} but this returns an error “TypeError: Cannot read property ‘frontmatter’ of undefined”.
I presume this is because, rather than rendering as an individual page, I’m trying to render this mardown inside a component using MDXRenderer. I’m guessing that in this case “props.pageContext…” doesn’t work.
(The actual use case is for a portfolio site - I’m trying to loop through all my “Work” markdown files on a single “Featured Work” page and render each one individually)
I expect that the way to do this is by passing the a variable using the MDXRenderer component. Something like:
<MDXRenderer category={work.frontmatter.category}>{work.body}</MDXRenderer>
But then I’m not sure how to access the category property inside my MDX markdown.
Question:
Is this the correct way to pass variables into my MDX code? Is what I want to do even possible? And if so, how do I then access the variables inside my MDX file?
Thanks in advance, B
Issue Analytics
- State:
- Created 4 years ago
- Comments:7 (2 by maintainers)
Top Related StackOverflow Question
Update:
After doing more searching I’ve found this thread on Spectrum that explained that any properties passed in <MDXRenderer> are available in the {props} object in the mdx file.
e.g. in my case I can do
<MDXRenderer frontmatter={work.frontmatter}>{work.body}</MDXRenderer>and then in the mdx markup I can add a component and use the {props} object. E.g.
<Socials links={props.frontmatter.socials}/>Funny, I could have sworn I tried that while I was debugging but apparently not well enough.
I still don’t see this information in the official docs, and it confused me until I find this thread. Mind I ask if I may add this as documentation for mdx in the Programmatically creating pages section as suggested by n-laverenko? I think it would help a lot of people.