Single Element Pattern (Singel) is a set of rules/best practices to create consistent, reliable and maintainable components in React and other component-based libraries. This is based on the idea that the building blocks of an application should resemble as most as possible native HTML elements. Read full article
This repo is a CLI tool for checking whether React components conform to the Singel pattern.
Installation
$ npm i -g singel
Usage
$ singel path/to/**/Component.js --ignore "path/to/**/ignored/Component.js"
Projects applying Singel
Feel free to send a PR adding your open source project
Rules
Render only one element
// bad - 2 elementsconst Element = <div > <span /> </div>; // goodconst Element = <div />; // good - if Element is goodconst Element2 = <Element />;
Never break the app
// goodconst Element = <div />; // bad - will break if getId wasn't providedconst Element = getId ...props <div = />; // bad - will break if foo wasn't providedconst Element = foo ...props <div = />;
Render all HTML attributes passed as props
// goodconst Element = <div />; // bad - not rendering idconst Element = id ...props <div />; // goodconst Element = id ...props <div = />;
Always merge the styles passed as props
// goodconst Element = <div />; // bad - not rendering classNameconst Element = className ...props <div />; // bad - not rendering styleconst Element = style ...props <div />; // bad - replacing className instead of appendingconst Element = <div ="foo" />; // bad - replacing style instead of mergingconst Element = <div = />; // goodconst Element = className ...props <div = />; // goodconst Element = style ...props <div = />;
Add all the event handlers passed as props
// goodconst Element = <div />; // bad - not passing onClickconst Element = onClick ...props <div />; // bad - replacing onClick propconst Element = <div = />; // goodconst Element = onClick ...props <div = />; // good - it's ok to replace internal event handlersconst Element = <div = />; // good - calling internal and propconst callAll = ...fns ...args fns; const Element = onClick ...props <div = />;
FAQ
How to handle nested elements?
Say you have a Button
element and you want to display a Tooltip
when it's hovered. The first rule you'll want to break is rendering only one element. To handle that you have some options:
- Use CSS pseudo-elements (such as
:after
and:before
); - Create a non-singel element, which is fine;
- Nest styles instead of components.
Here's an example of how you can accomplish tha latter one:
/* could also be CSS-in-JS */
const Button = className ...props <button = />; Button <div = />;
Usage:
<Button ="my-specific-button"> <Button.Tooltip ="my-specific-tooltip"> 😁 </Button.Tooltip> Hover me</Button>
Both Button
and Button.Tooltip
are single elements. You have all the benefits you would have by nesting them, but now with complete control over Button.Tooltip
from outside.
License
MIT © Diego Haz