What is Arrow function in React ? How is it used ?

  • They are more of a brief syntax for writing the function expression. It is also known as ‘fat arrow ‘(=>) the functions.
  • This keyword represented the object that called the function, which could be the window, the document, a button or whatever in a regular function.
  • It allows to bind the context of the components properly since in ES6 auto binding is not available by default.
  • While working with the higher-order functions, Arrow functions are most useful.
  • This keyword always represents the object that defined the arrow function in arrow function.

For example, in regular functions:

[pastacode lang=”markup” manual=”class%20Header%20%7B%0A%20%20constructor()%20%7B%0A%20%20%20%20this.color%20%3D%20%22Blue%22%3B%0A%20%20%7D%0A%0A%2F%2FRegular%20function%3A%0A%20%20changeColor%20%3D%20function()%20%7B%0A%20%20%20%20document.getElementById(%22demo%22).innerHTML%20%2B%3D%20this%3B%0A%20%20%7D%0A%7D%0A%0Aconst%20myheader%20%3D%20new%20Header()%3B%0A%0A%2F%2FThe%20window%20object%20calls%20the%20function%3A%0Awindow.addEventListener(%22load%22%2C%20myheader.changeColor)%3B%0A%0A%2F%2FA%20button%20object%20calls%20the%20function%3A%0Adocument.getElementById(%22btn%22).addEventListener(%22click%22%2C%20myheader.changeColor)%3B%0A” message=”” highlight=”” provider=”manual”/]

For example, in Arrow functions:

[pastacode lang=”markup” manual=”class%20Header%20%7B%0A%20%20constructor()%20%7B%0A%20%20%20%20this.color%20%3D%20%22Blue%22%3B%0A%20%20%7D%0A%0A%2F%2FArrow%20function%3A%0A%20%20changeColor%20%3D%20()%20%3D%3E%20%7B%0A%20%20%20%20document.getElementById(%22demo%22).innerHTML%20%2B%3D%20this%3B%0A%20%20%7D%0A%7D%0A%0Aconst%20myheader%20%3D%20new%20Header()%3B%0A%0A%0A%2F%2FThe%20window%20object%20calls%20the%20function%3A%0Awindow.addEventListener(%22load%22%2C%20myheader.changeColor)%3B%0A%0A%2F%2FA%20button%20object%20calls%20the%20function%3A%0Adocument.getElementById(%22btn%22).addEventListener(%22click%22%2C%20myheader.changeColor)%3B%0A%0A” message=”” highlight=”” provider=”manual”/]
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like

What is Prop Drilling ?

We pass a prop with another component with the help of all the components that come between, this method is known as prop drilling. Prop drilling is basically a situation…
View Answer

What is React DOM ?

It is an object which exposes a number of top level APIs to interact with the browser DOM. It provides DOM-specific methods that can be used at the top level…
View Answer

What is Flux ?

It is an application architecture that Facebook makes use of internally for constructing the client-side web application with React . It is a programming concept, where the data is a…
View Answer