- An ES2016 decorator is an expression which returns a function and can take a target, name and property descriptor as arguments.
- A decorator takes an argument (the function being decorated) and returns the same function with added functionality.
- Decorators are helpful for anything you want to transparently wrap with extra functionality.
- Its simplest form (React):
const HOC = (Component) => (props) => <Component {...props} />;
- Practical use case:
const Field = (Component) => ({
label,
error,
className,
inputClass,
disabled,
current,
...props
}) => (
<FormField label={label} error={error} className={className} disabled={disabled} current={current}>
<Component className={inputClass} disabled={disabled} {...props} />
</FormField>
)
-
The example above takes a
Component
as an argument, returns some props and then returns theComponent
using those props to alter it -
The primary benefit of the Decorator pattern is that you can take a rather vanilla object and wrap it in more advanced behaviors
-
The underlying code, or guts, of the object (
Component
) remains the same while the decorators provide a new skin. -
For instance a view which renders a plain window can have decorators to add different backgrounds, scroll bars, borders, etc.