React javascript question

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

im not exactly sure what you mean.

Below i quick made a class component. Are both handleClick functions the same? or does one need to be in one spot?

class App extends React.Component {
  constructor(props){
    super(props)
  }
  
  handleClick(){
    console.log('hello')
  }
  
  render(){
    const handleClick = ()=>{console.log('hello')};
    
    
    return (
    <div>
      
    </div>
       
    )
  }
}

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).

There is a challenge called Use Advanced JavaScript in React Render Method which shows this.

excellent. Thanks for your time helping with this

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();
  }
}

See Classes - JavaScript | MDN

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.