简体   繁体   中英

Simplify 3rd party component prop?

I'm using a React component, markdown-to-jsx , to turn markdown strings into HTML. It has the ability to take custom components I've created and use them to render Custom tags. However, the prop for doing so is so verbose that it's a bit annoying and I was hope to simplify it, but am having trouble achieving that.

example: I want to add a component, Dice, to my markdown render. This works perfectly, but wow, it's a lot of typing:

import Markdown from 'markdown-to-jsx';
import Dice from './Dice';
...
<Markdown options={{ overrides: { Dice: { component: Dice } } }}>
  {markdownContent}
</Markdown>

Wow, what if I had several components I wanted to add? Ugly. So, I had an idea: write a component that uses markdown-to-jsx and simplify the props:

import Markdown from 'markdown-to-jsx';
(other imports)
...

// Take the original component and run a map to create that ugly verbose code.
function Md({ components, children }) {
  const comps = components.map((c) => ({ [c.name]: { component: c } }));
  return <Markdown options={{ overrides: { comps } }}>{children}</Markdown>;
}

...
<Md components={[Dice, Attack, Foo]}>
  {markdownContent}
</Md>

Pretty cool, right? No. It doesn't work. I keep getting these errors:

  • <Dice /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.
  • Warning: The tag <Dice> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter

Why does the ugly version work but mine does not???

You're close, components.map returns an array but overrides needs an object, in your case you could use component.reduce to aggregate the values into an object instead.

const comps = components.reduce((accumulator, c) => { 
    accumulator[c.name] = {component: c};
    
    return accumulator;
}, {});

It also slightly affects the return statement:

return <Markdown options={{ overrides: comps }}>{children}</Markdown>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM