Skip Navigation

Count child elements HOC

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?

3 comments