Skip to content

Instantly share code, notes, and snippets.

@0bie
Last active September 21, 2022 18:00
Show Gist options
  • Save 0bie/e1bc75eae7df0ab1424eb46999a26a54 to your computer and use it in GitHub Desktop.
Save 0bie/e1bc75eae7df0ab1424eb46999a26a54 to your computer and use it in GitHub Desktop.
Working with decorators in React
  • 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 the Component 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.

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