1

I'm documenting a hook I've created with MDX, and I want to create a button that - when clicked - triggers this hook.

Basically, what I want is this

import { useMyHook } from './myHook';

# My hook
My hook is great. Check it out by clicking below:

{() => {
  const { triggerSomeAction } = useMyHook();
  return <button onClick={triggerSomeAction}>Click to demo</button>;
}}

Great right? It triggers some action when you click it!

Basically, I want to create a function component inline, and call it. What's the best way to achieve this?

I can wrap my expression in a React.Fragment and call React.createElement on it manually, but that seems like a rough implementation.

Edit: I can improve it even more by creating a wrapper component, InlineComponent, and wrap my code in it:

import { useMyHook } from './myHook';
import InlineComponent from './InlineComponent';

# My hook
My hook is great. Check it out by clicking below:

<InlineComponent>
  {() => {
    const { triggerSomeAction } = useMyHook();
    return <button onClick={triggerSomeAction}>Click to demo</button>;
  }}
</InlineComponent>

Great right? It triggers some action when you click it!

The implementation would simply be

const InlineComponent = ({ children }) => React.createElement(children);

However, this seems like a weird workaround for something that could be built in to the MDX framework somehow.

4

0 回答 0