rehypejs / rehype-react

plugin to transform to preact, react, vue, etc
https://unifiedjs.com
MIT License
391 stars 27 forks source link

Allow for properties to be set on the root node #11

Closed Everspace closed 6 years ago

Everspace commented 6 years ago

I might want to set the className or style on the div produced from an AST blob.

Like so:

// Ast.js
import React from "react"
import rehypeReact from "rehype-react"
import * as components from "components/markdownComponents"

const renderAst = new rehypeReact({
  components,
  createElement: React.createElement,
}).Compiler

const Ast = ({ ast, ...props }) => {
  ast.properties = props
  return renderAst(ast)
}

export default Ast

//gatsby page.js
import React from "react"
import { graphql } from "gatsby"
import Ast from "./Ast"

export const query = graphql`
  {
    allMarkdownRemark {
      edges {
        node {
          htmlAst
          frontmatter {
            title
          }
        }
      }
    }
  }
`

export default ({ data }) => {
  let result = data.allMarkdownRemark.edges
    .map({node: {htmlAst, frontmatter: {title}}} => (
      <div key={title}>
        <h2>{title}</h2>
        <Ast className="content" ast={htmlAst}/>
      </div>
    ))

  return result
}

This allows me to style a content block without an extra div nesting it, or perhaps tag and identify what came from renderAst()

rhysd commented 6 years ago

Thank you for this patch. Looks good.