Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why I can not use function keyword to define a function inside a reactjs class

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
     }
   }
} 
like image 553
Jack Avatar asked Nov 05 '19 16:11

Jack


People also ask

Why function keyword is not used in class in JavaScript?

Constructors and Classes However, the new class syntax does. Also, we can use the class method shorthand as we did with the greet method and we don't have to attach it to the prototype property of the class as its property. Therefore, once again, we don't need to function keyword as it's once again redundant.

Can you put a function in a class React?

That said, it's perfectly fine to declare functions inside a render method or more commonly these days a functional component. There are hooks like useCallback that can help with performance but 99% of the time it's not an issue.

Can we create function inside function in React?

It is possible, but it is not a good solution at all. Yeah, it creates new function on each re-render, but it's not a case if you don't pass them as props.

How do you call a function inside a React?

Example: Call a Function After Clicking a Buttonimport React from 'react'; function App() { function sayHello() { alert('Hello!' ); } return ( <button onClick={sayHello}> Click me!


1 Answers

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
  }
}
like image 89
Clarity Avatar answered Sep 28 '22 04:09

Clarity