Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Pranav Mathur
Pranav Mathur
1,061 Points

Can I use a simple JavaScript function (instead of Arrow fn) in a REACT app??

A normal JavaScript fn like, function name(){} instead of () => {}

2 Answers

Yes you can add a named function to your React class. In the example below I wrote the function add in my React class. You just don't have to put the word function in front of it. But when you want to call the add function, when you click on a button for example, you have to use an arrow function.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { number: 0 };
  }

  add() {
    this.setState(prevState => ({
      number: prevState.number+ 1
    }));
  }

  render() {
    return (
      <div>
        Number: {this.state.number}
        <button onclick={() => this.add()}>+1</button>
      </div>
    );
  }
}

ReactDOM.render(<App/>, mountNode);
Steven Parker
Steven Parker
231,269 Points

Why would you "have to" use an arrow function? It seems like you could replace the arrow function inside "add" also:

  add() {
    this.setState(function (prevState) {
      return { number: prevState.number + 1 };
    });
  }
Pranav Mathur
Pranav Mathur
1,061 Points

So that means, WE CAN use named functions inside components..?!

Yes you can use named functions inside a component. But if you want that the variable this points to the React component, you'll have to use the arrow functions

Steven Parker
Steven Parker
231,269 Points

My example is still anonymous, but it could have been named. And you can also give arrow functions names.

Steven Parker
Steven Parker
231,269 Points

The only concern I might have in replacing an arrow function with a conventional one would be if the code inside the function uses "this". An arrow function doesn't set "this" so it would have the same value as in the context of the definition, but a conventional function establishes a new value for "this".