Home > database >  Get a list of components and their props from MDX string - by regex?
Get a list of components and their props from MDX string - by regex?

Time:12-24

My problem - Get components & props from MDX/JSX string

I have an MDX string with Front-matter meta data in YAML, some regular text, some markdown and some React components.

I need to get the list of all React (non-HTML) components from it with their parameters.

So given this example:

---
title: Title of documents
tags: one, two, three
---

# My heading H1

Some text in paragraph. Than the list:
 - First item
 - Second item

More text with [a link](https://example.com).

<Articles category="theatre" count={3} />

Further text with more information.

<Newsletter categories={['theatre', 'design']} />

<MultilineComponent 
  paramA="A"
  paramB="B"
/>

<ComponentWithChildren param="value">
  Some children
</ComponentWithChildren>

... I would need this output:

[
  {
    component: 'Articles',
    props: {
      category: 'theatre',
      count: 3,
    },
  },
  {
    component: 'Newsletter',
    props: {
      categories: ['theatre', 'design'],
    }
  },
  {
    component: 'MultilineComponent',
    props: {
      paramA: 'A',
      paramB: 'B',
    }
  },
  {
    component: 'ComponentWithChildren',
    props: {
      param: 'value',
    }

  }
]

Also I need to do this on the server, so I don't have access to browser functionality (window, document, etc.).

What I've tried

Some basic Regex, but as I'm far from being professional in regexing, now I have two problems. :)

Is there some built in way how to parse JSX string to get a list of components & props in the way that I've described above? Or is there some maybe some other parser that I can use to solve this? If not, is there some Regex pattern I can use to get this?

Quick summary on "Why"

During the build of my Next.js project I need to determine which data is actually needed for each MDX page in the bundle. So if I see this in the Mdx file:

...other text

<Articles category="theatre" count={3} />

...other text

... which I'm somehow able to parse to this:

component: "Articles"
category: "theatre"
count: 3

that's enough info for me to know that I need to send those data to the page:

[
  {
    title: 'Romeo and Juliet',
    category: 'theatre',
  },
  {
    title: 'The Cherry Orchard',
    category: 'theatre',
  },
  {
    title: 'Death of a Salesman',
    category: 'theatre',
  }
]

Would you be able to help me with this? Thank you in advance!

  • Related