8

I have been confused about some syntaxes in ReactJS, one is that when I define a function inside one Reactjs class, I can not use function keyword, but when I moved the function outside the class then I have to add keyword function before the signature. Second is that if I write a function inside the render(), then I have to use arrow function. For example, why the following is wrong:

class Test extends Component{
   constructor(props){
      super(props)
   }
   function test(){
     //this is wrong,I need to remove function keyword
   }

   render(){
     mytest(){
      //also this is wrong,I only can use arrow function
     }
   }
} 
Jack
  • 5,540
  • 13
  • 65
  • 113
  • 4
    Because this is a class body and it expects to have *methods*. It's not allowed by the syntax of JS but also it doesn't have semantic sense - a function shouldn't have its own context, yet it will be bound to the class itself. – VLAZ Nov 05 '19 at 16:57
  • 4
    Note that this is not a React thing; it's basic JavaScript syntax. – Pointy Nov 05 '19 at 17:00
  • @VLAZ if possible , can you please provide any javascript docs or references to support your answer. it will be helpful – vijay kiran reddy Oct 12 '20 at 03:58
  • 1
    @vijaykiranreddy https://tc39.es/ecma262/#sec-function-definitions https://tc39.es/ecma262/#sec-class-definitions https://tc39.es/ecma262/#sec-method-definitions – VLAZ Oct 12 '20 at 04:57
  • https://stackoverflow.com/questions/31048953/what-do-these-three-dots-in-react-do/47944283#47944283 @VLAZ , can you pls help me with my doubt in the above link – vijay kiran reddy Oct 12 '20 at 08:55

1 Answers1

17

That's because your component is class based and has methods, not functions. To define a method you can do like so:

class Test extends Component {
  constructor(props) {
    super(props)
  }

  test() { // Defining method

  }

  render() {
    this.test() // can be called like this
  }
} 

If you want to be able to define functions inside a component you'll need to transform it to functional first:

function Test(props) {
  function test() {
    // This now works
  }
}
Clarity
  • 10,730
  • 2
  • 25
  • 35