Skip to content

Instantly share code, notes, and snippets.

@kylpo

kylpo/blog.md Secret

Created May 22, 2017 18:51
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kylpo/1ceacfab149b5fdfb5095c2c0cf9c7f5 to your computer and use it in GitHub Desktop.

Naming Convention for Injector Components

Huh? What is an "injector component"?

An injector component takes props, optionally computes new ones, then injects them into its child via React.cloneElement(). Crucially, it also does not add any new components to the DOM! It only exist in React's virtual DOM.

https://gist.github.com/74fe30085e5a9e8927a85d182a09265e

When Are Injector Components Useful?

In the prototyping framework, constelation, we use a LOT of injector components to abstract out logic and nicely separate concerns like style, animation, and interactions from our layout components.

React Native has also used this pattern in TouchableWithoutFeedback.

Here is an example render using many injector components:

https://gist.github.com/a2d3b0dfd03c04117f0ccb548e51bfa5

But here's the thing, which of these components are injectors? How many elements are actually added to the DOM?

The <Injector_ > Naming Convention

With constelation, we've chosen to denote injector components with a postfix _. Think of the postfix _ as being a blank space that needs to be filled by a child. Also, the name chains well. Below could read like: "an Evented, Animated, Styled View with a Text child"

https://gist.github.com/48e07eef013628c47a09a906cc57a9a0

Notice how much easier it is to identify the injectors? Also, we can now easily see that there are two elements added to the DOM (two do not have a postfix _).

It Gets Better

Can you spot the errors in this render?

https://gist.github.com/0123e23f2e4fedeaa11303b1495f4d31

Yes! Injector components should never be self-closing, and they should never wrap multiple children. We can fix this at code-time and not wait for the errors at runtime.

This naming convention helps developers understand the component's contract, and certainly would've helped me better understand what TouchableWithoutFeedback and TouchableOpacity are doing under the hood.

Even Better With Tooling

Naming conventions enable tooling. I've edited my vim color scheme to color injector components as props are colored, which further reinforces the concept and allows me to easily skim renders and identify them.

In the future, we could also create lint rules to identify errors at code-time using this convention.

more naming conventions => more helpful tooling


Note: I publish these to learn from your responses! Please let me know if you have any thoughts on the subject.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment