Reputation: 161
I have this class containing a string and the variable:
class Number extends Component{
var num = 8
render(){
return{
<Text>The number is: </Text> + num
}
}
}
However, I'm getting this error
Unexpected token (31:6)
var num = 8
^
Is there any way I can get the class to return both the text and the variable when used?
<Number/>
Upvotes: 1
Views: 2968
Reputation: 2440
In ES6 (the way you declared your class), you can't declare variables the way you want to. Here is explanation ES6 class variable alternatives
What you can do is to add it inside constructor, or inside render method.
class Number extends Component{
constructor(props){
super(props);
this.num = 8 // this is added as class property - option 1
this.state = { num: 8 } //this is added as a local state of react component - option 2
}
render(){
const num = 8; // or here as regular variable. option 3
return{
<Text>The number is: </Text> + this.num // for option 1
// <Text>The number is: </Text> + this.state.num //for option 2
// <Text>The number is: </Text> + num //for option 3
}
}
}
Upvotes: 5