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 trialBartlomiej Zabielski
Courses Plus Student 10,363 Pointsdeclaring functions and variable outside class react
Hey all,
I am reading the react docs and don't understand why the functions and variables in the codepen example are not declared inside the class.
https://codepen.io/gaearon/pen/WZpxpz?editors=0010
Does it have to do with context scope? not sure if im using term correctly what I mean is by declaring them outside the class the functions and variables are available to all components ?
I tried to add everything into the calculator class and it didn't work ><
this is the document page i was reading. https://reactjs.org/docs/lifting-state-up.html
2 Answers
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsMy guess is the reason they're not declared inside the class is that they don't have any reason to be in the class. For example this function:
function toFahrenheit(celsius) {
return (celsius * 9 / 5) + 32;
}
It takes it a celcius number and returns a fahrenheit number. This has nothing to do with React, and nothing to do with the component here. It's just math. Putting it inside the class would make the class more bloated, make it harder to maintain the code. In the real world, not in CodePen, we'd probably define that function in a separate file altogether and then import it into this one. There's a principle in software design called the separation of concerns.
You also mentioned that you tried to add everything into the calculator class and it didn't work. Can you post your code for that and the course or workshop that you're following along with? Also any error messages you're getting in the console would be helpful.
Bartlomiej Zabielski
Courses Plus Student 10,363 Pointshey thanks for reply. Its ok I try work it out (: I am still learning react going through all their documentation. thanks.