Skip to content

Instantly share code, notes, and snippets.

@pomber
Last active October 2, 2021 11:45
Show Gist options
  • Save pomber/df42194f72292feee5ceba74197128ee to your computer and use it in GitHub Desktop.
Save pomber/df42194f72292feee5ceba74197128ee to your computer and use it in GitHub Desktop.
Adding props to a JSX element with remark

This MDX file

import { MyComponent } from "my-component"

<MyComponent foo={[1, 2, 3]} />

Generates this mdxJsxFlowElement node in the MDAST:

{
  "type": "mdxJsxFlowElement",
  "name": "CH.Code",
  "attributes": [
    {
      "type": "mdxJsxAttribute",
      "name": "foo",
      "value": {
        "type": "mdxJsxAttributeValueExpression",
        "value": "[1, 2, 3]",
        "data": {
          "estree": {...}
        }
      }
    }
  ],
  "children": [],
  "data": {
    "_xdmExplicitJsx": true
  }
}

I want a remark plugin (it need to be in remark for other reasons) that adds the prop bar={[4,5,6]} to MyComponent. How do I generate the data.estree object for that expression?

My workaround now is to add this attribute:

{
  type: "mdxJsxAttribute",
  name: "bar",
  value: JSON.stringify([4,5,6])
}

And then in MyComponent use JSON.parse(bar).

@pomber
Copy link
Author

pomber commented Oct 2, 2021

@wooorm sugested to use estree-util-value-to-estree.

Adding a prop looks something like this:

import { valueToEstree } from "estree-util-value-to-estree"

const value = [4,5,6]

const data = {
  estree: {
    type: "Program",
    body: [
      {
        type: "ExpressionStatement",
        expression: valueToEstree(value),
      },
    ],
    sourceType: "module",
  },
}

node.attributes.push({
  type: "mdxJsxAttribute",
  name: "bar",
  value: {
    type: "mdxJsxAttributeValueExpression",
    value: JSON.stringify(value),
    data,
  },
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment