This may be a realy dumb question but in React class comonents. There are methods that are written after the constructor but before the render method that mostly are life cycle function but many times are regular event handling functions.
Then below the render and above the return there is space to write javascript and it seems to me that the same methods could also go there.
My question is that is there a reason why some javascript goes in one place and not the other?
At the end what react doing is creating an instance of your class and calling render method. And all the other methods used are called by the render method itself. But the order of writing the methods doesnt matter at all. Because your object instance initiated at the very beginning so are every methods. So even if I write a method after the render method and call it in the render method that doesnt throw any error. Hope you understood what I mean
I wouldn’t really suggest writing functions inside the render method.
But you can have expressions and they will be re-evaluated every time the render method is called (simply by the fact that the render method is called for you).
class Example {
methodAttachedToPrototype() {
console.log("I am a method attached to the prototype of `Example`, I am used by every instance of `Example`");
}
methodWithAFunctionInside() {
const exampleFunction = () => {
console.log("I am a function that gets created every time `methodWithAFunctionInside` is called");
};
exampleFunction();
}
}