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
}
}
}
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
}
}
}
Share
Improve this question
asked Nov 5, 2019 at 16:53
JackJack
5,89013 gold badges70 silver badges123 bronze badges
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. – VLAZ Commented Nov 5, 2019 at 16:57
- 5 Note that this is not a React thing; it's basic JavaScript syntax. – Pointy 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 – vijay kiran reddy 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 – VLAZ Commented Oct 12, 2020 at 4:57
- stackoverflow.com/questions/31048953/… @VLAZ , can you pls help me with my doubt in the above link – vijay kiran reddy Commented Oct 12, 2020 at 8:55
1 Answer
Reset to default 18That'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
}
}