5
Count child elements HOC (programming.dev)
submitted 2 months ago by [email protected] to c/[email protected]

I'm looking to write an HOC that counts and prints to the console the number of 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?

you are viewing a single comment's thread
view the rest of the comments
[-] [email protected] 2 points 2 months ago

Unfortunate, this seems like something that should be pretty trivial on the surface but I can see why I'd need a non react solution.

I'll probably break out of react and walk the dom, seems like it will work best for me.

Thanks for the help!

this post was submitted on 12 Mar 2025
5 points (100.0% liked)

React

1104 readers
1 users here now

A community for discussing anything related to the React UI framework and it's ecosystem.

https://react.dev/

Wormhole

[email protected]

Icon base by Skoll under CC BY 3.0 with modifications to add a gradient

founded 2 years ago
MODERATORS