How to accomplish default props with an MDX component? #2059
-
Say you have an MDX file like the following which uses a prop: # My Heading
My prop: {props.a} What would be the "MDX way" to set a default value for that prop? In a JSX file, I would do one of the following: export function MyComp({ a = "value", ...props }) {
return <div>My prop: {props.a}</div>
}
export function MyComp(props = { a: 'value' }) {
return <div>My prop: {props.a}</div>
}
export function MyComp(props) {
return <div>My prop: {props.a}</div>
}
MyComp.defaultProps = { a: 'value' } I've experimented quite a bit and searched around but am still at a loss for how to do that in MDX (if it's even possible). If it's not currently possible, would it make sense to create a plugin that allows you do something like this? # My Heading
My prop: {prop.a}
export function getDefaultProps(props) {
return { ...props, a: 'value' }
} I'm imagining I that it would automatically get called inside of MDXContent like this or something: export function MDXContent(initialProps) {
const props = getDefaultProps(initialProps)
return <>
<h1>My Heading</h1>
My prop: {props.a}
</>
} It might even be something that should be supported natively in MDX, would you accept a PR to add it? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 18 replies
-
So taking a step back, how are you using MDX in the broader context of your application. It's also worth nothing that there are a few options which could work with MDX today, without modifications. first option - a get prop utilityIf you don't want to customize MDX, and want the props to apply to all usages automatically, something like: export function getProp(props, name) {
const defaultProps = {
// put defaults here
}
return {...defaultProps, ...props}[name]
}
# My Heading
My prop: {getProp(props, 'a')} second option - nullish coalesingIf a prop is only used in one place: # My Heading
My prop: {props.a ?? 'test'} or # My Heading
My prop: {props.a || 'test'} can be used third option - create an ESAST pluginESAST plugins allow the final javascript generated to be modified via an AST.
I'm open to discussing it. |
Beta Was this translation helpful? Give feedback.
So taking a step back, how are you using MDX in the broader context of your application.
Generally, I've seen and used MDX to generate pages or content items.
But it sounds like you are interested in using it more a generic component builder? (Is that accurate?)
It's also worth nothing that there are a few options which could work with MDX today, without modifications.
first option - a get prop utility
If you don't want to customize MDX, and want the props to apply to all usages automatically, something like: