ES7 Decorators

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.

Exploring EcmaScript Decorators

https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841

ES7 Decorators in ReactJS

https://medium.com/@jihdeh/es7-decorators-in-reactjs-22f701a678cd

Need a plugin from Babel

npm install babel-plugin-transform-decorators-legacy

Create a decorator

//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>
           )
        }
     }
 }

Use the decorator

//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>
   )}
}

That's it.

results matching ""

    No results matching ""