Home > OS >  Reactjs : why const is not allowed in react class?
Reactjs : why const is not allowed in react class?

Time:06-28

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 [email protected] 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; 
      }
   }

CodePudding user response:

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; 
   }
}

CodePudding user response:

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;
  • Related