0

Why react class const is not allowed ? if i am assigning template_counter and return in render method getting error : SyntaxError: src/index.js: Unexpected token . I am using babel-cli@6.24.1 to convert this react code.

  class Counter extends React.Component{
     const template_counter = (<div><h1>Counter Component</h1><p>count : 0 </p></div>);
     render(){
          return this.template_counter; 
      }
   }
Prabhat Yadav
  • 1,181
  • 6
  • 18
  • 29
  • Related: https://stackoverflow.com/questions/43766867/how-to-define-class-level-constant-in-es6-class – jarmod Jun 27 '22 at 19:46
  • why are you going react class ? if I might ask ? – Richardson Jun 27 '22 at 19:50
  • The TL;DR is that this just isn't how JS works. What makes the most sense here depends on what you actually want to do; this construct doesn't make a lot of sense for multiple reasons--as written there's no good reason to separate the JSX from `render` in the first place. What is your actual goal? What is the intent behind this? – Dave Newton Jun 27 '22 at 19:52

2 Answers2

1

Add the const inside the render() function. You can't have const variables in classes (they won't be set on this anyway)

class Counter extends React.Component{
     render(){
          // you can just return the assignation without assigning it here
          const template_counter = (<div><h1>Counter Component</h1><p>count : 0 </p></div>);
          return template_counter; 
      }
   }

OR remove const to have it put on this

class Counter extends React.Component{
   template_counter = (<div><h1>Counter Component</h1><p>count : 0 </p></div>);
   render(){
       return this.template_counter; 
   }
}
0

As your are using class component so you need to directly assign data to variable or you can use constructor for define your data.

using constructor

import React from "react";

class Counter extends React.Component{
  constructor(){
    super();
    this.template_counter = (<div><h1>Counter Component</h1><p>count : 0 </p></div>);
  }
  render(){
       return this.template_counter; 
   }
}

export default Counter;

without constructor

import React from "react";

class Counter extends React.Component{
  template_counter = (<div><h1>Counter Component</h1><p>count : 0 </p></div>);
  render(){
   return <div>{this.template_counter}</div>
  }
}

export default Counter;