Gia Thinh Nguyen
Published on
In certain scenarios, we might want to have a little bit more control over the
children
being rendered in a functional component. This can be achieved with a
combination of React.Children.map()
and React.cloneElement()
which allows us
to dynamically pass additional props to child elements that maybe only the parent
component would know about.
I found this to be quite useful when working with a sub-component pattern with JSX Dot Notation where a single component delivers multiple sub-components that need to adhere to a certain hierarchy during usage. This comes with the slight caveat of not exactly knowing this hierarchy before hand without reading through some documentation.
A simple example would be nesting a <div>
element inside a <p>
element, which
is clearly invalid HTML and the console will throw an error for that mistake.
Similarly for functional components, we can add in some defensive programming by
throwing a warning to the console whenever our component encounters a child
element that should not be rendered when using this method of mapping Children.