React "clean" practices pt2:Composition
In today’s lesson you will learn how to build components in React using the “composition” technique. This technique allows you to keep the “S” in S.O.L.D while building scalable applications with React. Let start with an example Button component.
Currently our button component has six props which means it has six concerns:
Here’s what our button looks like when used in our App.tsx file
领英推荐
That's a lot of concerns for one component. There’s also the possibility that you may want greater flexibility down the road. For example, you may want a button on a page without an icon. This means more internal logic and thus more complexity for our button to be concerned with. By using a technique called “composition”, we can create a button out of multiple components. Lets look at an example:
Here we have three components: AppButton, AppText, and AppIcon. Creating multiple components allows for separation of concerns. Our AppButton is concerned with its functionality as a “parent” pressable component(positioning of children, handlers...). Our AppText component is concerned with things related to text(color, font size,....) and our AppIcon with things related to rendering an icon. Lets see the visual difference between our new component and our old component.
Instead of having one big component with multiple concerns, we have a “parent” component with its “children” components who are concerned with their own needs. If you believe this will add value to the dev community, please share!