Skip to content

Instantly share code, notes, and snippets.


kylpo/ Secret

Created May 22, 2017
What would you like to do?

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.

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:

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"

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?

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