Skip to content

Commit

Permalink
Refactor mdx-renderer to use hooks (gatsbyjs#333)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandernanberg authored and ChristopherBiscardi committed Jun 27, 2019
1 parent d92a819 commit 9482942
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 29 deletions.
12 changes: 5 additions & 7 deletions packages/gatsby-plugin-mdx/context.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
/* eslint-disable */
import React, { createContext } from "react";
import React, { createContext, useContext } from "react";

const GatsbyMDXScopeContext = createContext({});

export const withMDXScope = Component => ({ scope, ...props }) => (
<GatsbyMDXScopeContext.Consumer>
{contextScope => <Component scope={scope || contextScope} {...props} />}
</GatsbyMDXScopeContext.Consumer>
);
export const useMDXScope = scope => {
const contextScope = useContext(GatsbyMDXScopeContext);
return scope || contextScope;
};

export const MDXScopeProvider = ({ __mdxScope, children }) => (
<GatsbyMDXScopeContext.Provider value={__mdxScope}>
Expand Down
51 changes: 29 additions & 22 deletions packages/gatsby-plugin-mdx/mdx-renderer.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,33 @@
const React = require("react");
const { withMDXComponents, mdx } = require("@mdx-js/react");
const { withMDXScope } = require("./context");
const { useMDXComponents, mdx } = require("@mdx-js/react");
const { useMDXScope } = require("./context");

module.exports = withMDXScope(
withMDXComponents(({ scope = {}, components = {}, children, ...props }) => {
if (!children) {
return null;
}
const fullScope = {
// React is here just in case the user doesn't pass them in
// in a manual usage of the renderer
React,
mdx,
...scope
};
module.exports = function MDXRenderer({
scope = {},
components = {},
children,
...props
}) {
const mdxComponents = useMDXComponents(components);
const mdxScope = useMDXScope(scope);

// children is pre-compiled mdx
const keys = Object.keys(fullScope);
const values = keys.map(key => fullScope[key]);
const fn = new Function("_fn", ...keys, `${children}`);
if (!children) {
return null;
}

const End = fn({}, ...values);
return React.createElement(End, { components, ...props });
})
);
const fullScope = {
// React is here just in case the user doesn't pass them in
// in a manual usage of the renderer
React,
mdx,
...mdxScope
};

// children is pre-compiled mdx
const keys = Object.keys(fullScope);
const values = keys.map(key => fullScope[key]);
const fn = new Function("_fn", ...keys, `${children}`);

const End = fn({}, ...values);
return React.createElement(End, { components: mdxComponents, ...props });
};

0 comments on commit 9482942

Please sign in to comment.