7
7
75db772019-09-03 22:28:01
React
75db77, 2019-09-03 22:28:01

Is it possible to write functions in React this way?

There is such a function in the code:

handleClick = () => {
    this.setState(state => ({ isActive: !state.isActive }));
 };

But I really dislike arrow functions, I always write ordinary functions in pure JS.
And I decided to throw this function on the Babel website.
This is how he translated this function into a regular one:
handleClick = function handleClick() {
   this.setState(function (state) {
    return {
      isActive: !state.isActive
    };
  });
};

Did Babel translate correctly?
Although in theory I think I should have translated something like this:
handleClick = function() {
   this.setState(function (state) {
    return {
      isActive: !state.isActive
    };
  });
};

And another question:
Is it possible to write functions like this according to React rules? That is, to have the word function and return?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artur, 2019-09-03
@artur_kudaev

Is it possible to write functions like this according to React rules? That is, to have the word function and return?
You can use pure js in react

R
Roman Alexandrovich, 2019-09-04
@RomReed

Nobody forbids you to write functions with the word function and return. But you should understand that when you write arrow functions you don't have a problem with context loss, but when you write functions like this

handleClick = function() {
   this.setState(function (state) {
    return {
      isActive: !state.isActive
    };
  });
};

then you have to bind the context either with .bind or in the constructor so Agree arrow functions are a better option for this. this.handleClick=this.handleClick.bind()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question