DEV Community

Cover image for React.js ~Tips for making UI that is reusable and testable~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

React.js ~Tips for making UI that is reusable and testable~

If you participate in a project or see the codebases of OSS project, you come across UI to tackle complex specifications.

Here are specific cases below.

  • The bundle size is getting too large.

  • High maintenance and upkeep costs

    • You have to ask what the component does.
    • It is difficult to understand what the component does if you ask.
  • Low reusability

    • There are too many criteria to use the component, and it follows that you make a similar one.
  • Complex API

    • There are so many props that you can’t count them all on the fingers of one hand.
    • It's hard to determine whether we can implement the use case using existing features.

To deal with these issues, here are some solutions bellow.

No.1 Weather HTML and CSS have a single responsibility.

<Button
  prefix={helpIcon}
  surfix={heartIcon} 
  hover={filledHelpicon}
  text="hello" 
  color="green" 
  primary={true}
  toolip={<Tooltip/>}
  onClick={handleClick}
  ...
/>

Enter fullscreen mode Exit fullscreen mode

This is close to the extension of OBJ programming.
This Button component has multiple responsibilites such as rendering Icon component and Tooltip component in addition to rendering Button component itself.

Therefore, you should care for combining rather than extesion.
You should not pass them as props, but children.

<Button 
  primary
  onClick={handleClick}
>
  <HelpIcon/>
  <InnerText color="green">hello</InnerText />
  <HeartIcon />
</Button>

Enter fullscreen mode Exit fullscreen mode

Furthermore, while JavaScript successfully separates concerns and responsibilities, I often see UIs where the roles of HTML and CSS are not separated—appearance, structure, interactions, and spacing are all implemented using a single selector and deeply nested CSS.
To tackle complex specifications, we must implement HTML and CSS in accordance with the Single Responsibility Principle. Being mindful of the Single Responsibility Principle will also help reduce redundant and unnecessary CSS.

Top comments (0)