10

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
     }
   }
} 
5
  • 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. Commented Nov 5, 2019 at 16:57
  • 5
    Note that this is not a React thing; it's basic JavaScript syntax. Commented Nov 5, 2019 at 17:00
  • @VLAZ if possible , can you please provide any javascript docs or references to support your answer. it will be helpful Commented Oct 12, 2020 at 3:58
  • 1
    @vijaykiranreddy tc39.es/ecma262/#sec-function-definitions tc39.es/ecma262/#sec-class-definitions tc39.es/ecma262/#sec-method-definitions Commented Oct 12, 2020 at 4:57
  • stackoverflow.com/questions/31048953/… @VLAZ , can you pls help me with my doubt in the above link Commented Oct 12, 2020 at 8:55

1 Answer 1

18

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
  }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Just quickly want to add that it is also possible to use arrow functions in functional components. As in const test = () => { // this now works }
@Julian, but without the const part :)
@devserkan No, the const part is needed :)
It's possible to have both arrow functions in functional and methods in class based components.
Ah, I missed the "functional components" part. My bad @Julian :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.