I’m looking to write an HOC that counts and prints to the console the number of <h1/> elements in the wrapped component. For example:

const Foo: FC<{}> = ({}) => {
    return (
        <div>
            <h1>Foo</h1>
            <p>Bar</p>
        </div>
    )
}


export default countH1(Foo)

this should print 1 and then return Foo as is for rendering.

React.Children.forEach(child => {...})

seems to be about the explicit children property and not descendant html elements. How can I achieve this?

  • brian
    link
    fedilink
    arrow-up
    1
    ·
    44 minutes ago

    there’s sort of ways to achieve this but none of them good react. what’s the actual goal?

    • zamithalOP
      link
      fedilink
      arrow-up
      1
      ·
      38 minutes ago

      The intent of this hoc is to generate a minimap for the wrapped component, it walks down the tree finding all h1, h2 etc components and generates a new minimap (a list of clickable links to the sections) from that data in a fragment. That fragment is then rendered.