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 trialPaul Brown
7,057 PointsReact.createClass -- methods return () vs. return {} -- Confused!
Working thru the React Basics videos and now on "Understanding State" and ran into the following. When first trying to write getInitialState I followed the syntax of the render function, using parentheses. It didn't work. Took me a bit to figure out where my code was different from Instructor Jim Hoskins' code.
What's the explanation for when to use parens and when to use curly braces?
Thanks in advance!
getInitialState: function() {
return {
score: 0
};
},
vs.
render: function() {
return (
<div className="counter">
<button className="counter-action decrement"> - </button>
<div className="counter-score">{this.state.score}</div>
<button className="counter-action increment"> + </button>
</div>
);
},
1 Answer
Ari Misha
19,323 PointsHiya there! Before answering your question, I wanna point something that is important: The createclass() method will deprecate in near future so if you wanna create components with React, you should learn ES6 class implementation 'coz its here to stay and its best practice and there are so many advantages to it as well. And I wanna request to Treehouse to update their course, teach what is recommended and best practices.
Now, lets jump to your question. In the first example, the getInitialState() returns a state which is an object contains key/value pair. Whereas in the second example, render() method returns a JSX virtual DOM wrapped within div tags. When creating a component in React, return method is important 'coz these are reusable functions/components. And sometimes when dealing with states and State management Libraries like MobX or Redux or Flux, you need to implement pure high order functions or just functions, that returns state which is simply an object contains info about stuff. I hope that helps!
~ Ari