The more I develop with React the more I learn about creating truly dynamic outputs and making components reusable in many different situations. Doing this requires more and more React knowledge and a real dedication to design when thinking about refactoring a component.
As components start to get too large they give off a bad ‘code smell’ and beg for refactoring. Shrinking and separating these can help make the app easier to understand and these smaller components can often be reused in other places in the application if designed right,
While trying to improve an application I ran into a situation where my component didn’t know its children ahead of time. The component was essentially a container for holding other elements.
Using the children prop allows other components to pass arbitrary children to them by nesting the JSX.
The ReactJS docs use an example of a custom border. By rendering the children prop in the Border component you can then pass children to the border by nesting them directly inside the JSX of another component.
Anything inside of the FancyBorder
component JSX tag gets passed to the Border component as a children prop. If we render the props.children
inside a <div>
we will see everything nested in the FancyBorder
component’s final output.
After learning about props.children
and starting to implement it to solve problems I understood where it could be used to allow for more refactor and increase the ability to reuse simple UI components.
Happy Hacking!
Resources:
Let’s Connect: