EmpJemz
EmpJemz

Reputation: 88

What does "SomeName => {}" mean?

I'm new to react coming from a .Net background and I was trying to create a class, I tried numerous ways of doing so but in this instance I was unable to create a constructor in this variation and came to the conclusion that this maybe isn't a class, I've searched around the web but haven't found any info

Here is an example:

   export default ViewTestStuff => {

     constructor(){
       // errors
       }
        return (
            <div>
                <p>Hello</p>
            </div>
        )
    }

so my question is what is the "=> {}" in this example, is this a class? and why can't I create a constructor in it if it is indeed a class

Upvotes: 0

Views: 83

Answers (3)

Luke
Luke

Reputation: 8407

It is a Arrow Function from es6, and has nothing to do with React.js

const add = (a, b) => a+b;

it is just a function.

calling add(2, 3) returns 5

One important thing to remember is, that arrow functions do not have the prototype chain. You also cannot call them with new.

Another thing to notice is, that this is bound to the context where the arrow function is defined.

const obj = {
    name: "Lukas",
    method: function() {
        var self = this;
        console.log(this.name === "Lukas");
        return [
          function() {
              console.log(this !== self)
          }, 
          () => {
              console.log(this === self)
          }
        ];
    }
}

const [func, arrow] = obj.method();

func();
arrow();

see the docs

Upvotes: 1

Murilo Cruz
Murilo Cruz

Reputation: 2551

It is an arrow function! A nice feature on ES6, that is already implemented on most modern browsers.

Something => {} Means a function with Something as it's parameter and an empty body. It is similar to:

function (Something) {
}

In your case, it's the same as:

export default function (ViewTestStuff) {

 constructor(){
   // errors
   }
    return (
        <div>
            <p>Hello</p>
        </div>
    )
}

And it's indeed invalid.

Upvotes: 1

Magdalena Rumakowicz
Magdalena Rumakowicz

Reputation: 97

This is not a React thing... arrow functions are new in es6 javascript. More info can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Upvotes: 0

Related Questions