Decorators and React Components
Decorators are a syntax for calling higher order functions. Typically, a decorator is just a function which takes another function and extends the latters behavior. We can use decorators to reduce boilerplate by easily adding reusable behaviors to React components.
Decorators are available using the ES7 syntax so you need an npm plugin such as the babel-plugin-transform-decorators-legacy
to transpile it.
The following is a very simple example of simply outputting the decoratored components props to the console so we get an idea of how this can work.
Every instance of <Car />
will now output its props to the console.
Arguments
Taking this example further, we can pass arguments to the decorator. In this example, the decorator accepts a callback function which we use to pass in the function warn
which simply outputs the components props via console.warn
.