Home > Enterprise >  What is this React syntax – <ReactMarkdown components={{pre() {}}} />?
What is this React syntax – <ReactMarkdown components={{pre() {}}} />?

Time:04-20

While exploring the react-markdown package, I noticed it has a strange way to customize components. It has props components and it accepts an object, but the syntax looks nothing like the regular key: value object syntax.

    <ReactMarkdown
      children={markdown}
      components={{
        pre({node, inline, className, children, ...props}) {
          return children;
        }
      }}
    />

Now, this does work, but I don't understand how. Is it possible to turn this into a regular key: value syntax?

CodePudding user response:

The double curly braces could be intimidating but it's just a regular object being passed as prop, it has pre key that is a function, you could rewrite it like this:

const componentsObject = {
  pre: ({ node, inline, className, children, ...props }) => children,
};

return <ReactMarkdown children={markdown} components={componentsObject} />;

Demo: https://stackblitz.com/edit/react-dn2f8d?file=src/App.js

  • Related