Mdx: Add support for js code in mdx

Created on 19 Sep 2019  路  3Comments  路  Source: mdx-js/mdx

Subject of the feature

It would be nice to add a syntax for inline js, this is partularly useful with the new hooks to allow for intractive documentation. I propose wrapping such blocks in {{ }}

Expected behavior

Given

import { useState } from 'react';
# Stuff
{{ const [state, setState] = useState(); }}
<input value={state} onChange={(e) => setState(e.currentTarget.value)}/>

The output would be

/* @jsx mdx */
import { useState } from 'react';
const makeShortcode = name => function MDXDefaultShortcode(props) {
  console.warn("Component " + name + " was not imported, exported, or provided by MDXProvider as global scope")
  return <div {...props}/>
};
const layoutProps = {

};
const MDXLayout = "wrapper"
function MDXContent({
  components,
  ...props
}) {
  const [state, setState] = useState();
  return <MDXLayout {...layoutProps} {...props} components={components} mdxType="MDXLayout">
    <h1>{`Stuff`}</h1>
    <input value={state} onChange={(e) => setState(e.currentTarget.value)} />
    </MDXLayout>;
}
;
MDXContent.isMDXComponent = true;

Alternatives

Using context works but not well, you need to jump though some hoops to get the syntax to work right

馃毇 statuwontfix

Most helpful comment

This is what I do:

export const Stuff = () => {
  const [state, setState] = useState();
  return <input value={state} onChange={(e) => setState(e.currentTarget.value)} />
}

<Stuff />

It forces you to encapsulate your code, which is good.

All 3 comments

This is what I do:

export const Stuff = () => {
  const [state, setState] = useState();
  return <input value={state} onChange={(e) => setState(e.currentTarget.value)} />
}

<Stuff />

It forces you to encapsulate your code, which is good.

Slightly related: MDXC (which predates MDX by few months) had extra syntax for declaration of props:

prop value
prop onChange

<input
  value={value}
  onChange={onChange}
/>

<p>{value && `Hello, ${value}!`}</p>

Thanks for the input folks! Going to close this since you can achieve js via exports as @mlajtos mentions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

aseeeem picture aseeeem  路  3Comments

mAAdhaTTah picture mAAdhaTTah  路  4Comments

codebender828 picture codebender828  路  4Comments

francisfuzz picture francisfuzz  路  4Comments

silvenon picture silvenon  路  4Comments