ES7 Decorators in ReactJS

So while working on a mini reactJS experiment, i found myself wanting to add a NavBar across multiple pages and not add it on some pages.

Now one way i thought of and what most people would do is create a react component, and add it where you need it, that’s fine, it works.

[homepage.js, ...etc]
render (
<NavBar />
...
)

But what if, just what if you are like me who just likes to experiment and try to keep code smooth to the eyes, keeping common logic in some cold place. That’s what lead me to using ES7 decorators.

And what is this Decorator thing?

According to an excerpt i read from a post on decorators by Addy Osmani

A Python decorator is a function that takes another function, extending the behavior of the latter function without explicitly modifying it.

Decorators are helpful for anything you want to transparently wrap with extra functionality. These include memoization, enforcing access control and authentication, instrumentation and timing functions, logging, rate-limiting, and the list goes on.

You can read more about decorators from that post.

Implementing Decorators in ReactJs

Let’s say you have your react application all set up, and now you want to try using the decorators.

You would be needing a plugin from Babel to be able to use this decorator feature.

npm install babel-plugin-transform-decorators-legacy

//create a file, e.g decorator/navbar.js
import React, {Component} from "react";
export default function navBar() {
    return function(Child) {
      return class extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h2>Hello this is the navigation bar</h2>
<Child />
</div>
)
        }
}
}

And there my friends is a simple ES7 decorator in reactJS.

The concept might look a little familiar if you know currying.

An important thing to note, is the Child parameter passed into the returned function and the <Child /> . One best way to understand this is like doing this.props.children

For example, if you then want to use the decorator you have created in another component,

//anotherComponent.js
import React, {Component} from "react";
import navBar from "./decorator/navBar";
@navBar()
class AnotherComponent extends Component {
render() {
return(
<div>
<p>Hello World</p>
</div>
)}
}

Now that is a very simple decorator function in reactJS. You should note that you do not really need decorators, you can just use it if you’re feeling adventurous, have an eye for functional programming and higher other components.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.