React "clean"? practices 
                  pt2:Composition

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.

No alt text provided for this image

Currently our button component has six props which means it has six concerns:

  1. text - concerned with the text that will inform the user with instructions
  2. icon - concerned with rendering an icon for better user experience?
  3. pressableStyle - concerned with how the button will look
  4. viewStyle - concerned with how the how the text and icon will look
  5. textStyle - concerned with how the text will look
  6. onPress - concerned with how the button will function

Here’s what our button looks like when used in our App.tsx file

No alt text provided for this image

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:

No alt text provided for this image

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.

No alt text provided for this image

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!

要查看或添加评论,请登录

社区洞察

其他会员也浏览了