How to convert arrow Function to ES5 function in react

Asked
Active3 hr before
Viewed126 times

10 Answers

convertarrowreactfunction
90%

wrap the 2 adjacent JSX elements with a common parent element. ,wrap { } around 'Welcome'.concat(subject) and description.,You need to do following steps:

var Welcome = function({subject, description}) {
   return(
     <div>
        <Person title={ 'Welcome'.concat(subject) }/>
        <Profile description={description}/>
     </div>
   );
};
load more v
88%

Here’s an example of the type of bug that arrow functions prevent. At first glance, you may expect the button’s background color to change to red when you click it. But if you actually click the button, you’ll find that nothing changes…,For example, you could fix the bug in the first example by redefining handleClick as an arrow function method:,So to wrap things up, here are the three rules of arrow functions:

import React from 'react'
import ReactDOM from 'react-dom'

class BrokenButton extends React.Component {
  render() {
    return (
      <button onClick={this.handleClick} style={this.state}>
        Set background to red
      </button>
    )
  }

  handleClick() {
    this.setState({ backgroundColor: 'red' })
  }
}

ReactDOM.render(
  <BrokenButton />,
  document.getElementById('root')
)
load more v
72%

An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations. , As stated previously, arrow function expressions are best suited for non-method functions. Let's see what happens when we try to use them as methods: ,Let's decompose a "traditional function" down to the simplest "arrow function" step-by-step:

// Traditional Function
function(a) {
   return a + 100;
}

// Arrow Function Break Down

// 1. Remove the word "function" and place arrow between the argument and opening body bracket
(a) => {
   return a + 100;
}

// 2. Remove the body braces and word "return" -- the return is implied.
(a) => a + 100;

// 3. Remove the argument parentheses
a => a + 100;
load more v
65%

With functions and ES6 classes defaultProps is defined as a property on the component itself:,With createReactClass(), you need to define getDefaultProps() as a function on the passed object:,In ES6 classes, you can define the initial state by assigning this.state in the constructor:

class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
load more v
75%

ES6 introduced classes.,Variables (let, const, var),Arrow functions were introduced in ES6.

A simple class constructor:

class Car {
   constructor(name) {
      this.brand = name;
   }
}
load more v
40%

NOTE: This plugin is included in @babel/preset-env,Add names to arrow functions.,async-generator-functions

In

var a = () => {};
var a = b => b;

const double = [1, 2, 3].map(num => num * 2);
console.log(double); // [2,4,6]

var bob = {
   _name: "Bob",
   _friends: ["Sally", "Tom"],
   printFriends() {
      this._friends.forEach(f => console.log(this._name + " knows " + f));
   },
};
console.log(bob.printFriends());

Out

var a = function() {};
var a = function(b) {
   return b;
};

const double = [1, 2, 3].map(function(num) {
   return num * 2;
});
console.log(double); // [2,4,6]

var bob = {
   _name: "Bob",
   _friends: ["Sally", "Tom"],
   printFriends() {
      var _this = this;

      this._friends.forEach(function(f) {
         return console.log(_this._name + " knows " + f);
      });
   },
};
console.log(bob.printFriends());
npm install--save - dev @babel / plugin - transform - arrow - functions

Without options:

{
   "plugins": ["@babel/plugin-transform-arrow-functions"]
}

With options:

{
   "plugins": [
      ["@babel/plugin-transform-arrow-functions", {
         "spec": true
      }]
   ]
}
babel--plugins @babel / plugin - transform - arrow - functions script.js
require("@babel/core").transformSync("code", {
   plugins: ["@babel/plugin-transform-arrow-functions"],
});

Using spec mode with the above example produces:

var _this = this;

var a = function a() {
   babelHelpers.newArrowCheck(this, _this);
}.bind(this);
var a = function a(b) {
   babelHelpers.newArrowCheck(this, _this);
   return b;
}.bind(this);

const double = [1, 2, 3].map(
   function(num) {
      babelHelpers.newArrowCheck(this, _this);
      return num * 2;
   }.bind(this)
);
console.log(double); // [2,4,6]

var bob = {
   _name: "Bob",
   _friends: ["Sally", "Tom"],
   printFriends() {
      var _this2 = this;

      this._friends.forEach(
         function(f) {
            babelHelpers.newArrowCheck(this, _this2);
            return console.log(this._name + " knows " + f);
         }.bind(this)
      );
   },
};
console.log(bob.printFriends());
load more v
22%

With ES6 you now have another options for creating Javascript functions. You are probably familiar with the ES5 way of creating a function with the ‘function’ keyword.,Or you could even set the value of ‘this’ to a variable inside the first function and reference it in the second function,Arrow functions in ES6 allow you to remove some of that syntax along with refining how to handle ‘this’.

With ES6 you now have another options for creating Javascript functions. You are probably familiar with the ES5 way of creating a function with the ‘function’ keyword.

function sayHi(greeting) {
   return greeting;
}
sayHi('Hello!'); // 'Hello!'
load more v
60%

The second way, available starting ES2015, is the arrow function syntax:,The first, usual way, is by using the function keyword:,...args rest parameter collects the execution arguments of the arrow function: ['c', 'd'].

// Function declaration
function greet(who) {
   return `Hello, ${who}!`;
}
load more v
48%

Now, you can quickly see how the outer function greeter has a parameter, greeting, and returns an anonymous function. This inner function in its turn has a parameter called name and returns a string using the value of both greeting and name. Here’s how you can call the function:,Need fast data interactions in your Node app? Learn how Redis speeds caching, message brokering, sessions, analytics, streaming and more.,But what if you really want to use an arrow function to replicate the same functionality? One thing you can do is use ES6 rest parameters (...). Here’s how you could rewrite your function:

Pretag
 Pretag team - issue, fix, solve, resolve
23%

You can see that in the following ES5 code:,These roles clash: Due to roles 2 and 3, functions always have their own this. But that prevents you from accessing the this of, e.g., a surrounding method from inside a callback (role 1).,With an arrow function, the code looks as follows.

const arr = [1, 2, 3];
const squares = arr.map(x => x * x);

// Traditional function expression:
const squares = arr.map(function(x) {
   return x * x
});
load more v

Other "convert-arrow" queries related to "How to convert arrow Function to ES5 function in react"