Home > Back-end >  ReactJs: Unexpected token on Class component
ReactJs: Unexpected token on Class component

Time:10-25

I have a class which is a simple Event Handling component in React. When I try to return a div component to wrap the small input form I get an error Unexpected token and JSX expression must have one parent on the h2 element. I have commented on the code where the error occurs.

import React, {Component} from "react"



// Event to change text and show on browswer

class EventManage extends Component{
  constructor(props){
    super(props);
    this.state ={
      developerName:""
    };
  }
  changeName(event){
    this.setState({
      developerName:event.target.value
    });
  }
  return(

      <div>        //This is where the error occurs (Unexpected tocken)

        <h2> Simple Event Handling </h2>    // JSX must have one parent

        <label htmlFor = "Name">Enter Your Name </label>
        <input type = "text" id = "devName" onChange={this.changeName.bind(this)}/>
        <h1>Hello Developer {this.state.developerName} Happy Coding </h4>

      </div>
  );
}
export default EventManage;

CodePudding user response:

Like Terry said Use render():

.
.
  changeName(event){
    this.setState({
      developerName:event.target.value
    });
  }

render(){
 return (
  <div>


  </div>

 );
}
.
.

CodePudding user response:

Finally saw the error: Using class components render should be used before return statement

import React, {Component} from "react"



// Event to change text and show on browswer

class EventManage extends Component{
  constructor(props){
    super(props);
    this.state ={
      developerName:""
    };
  }
  changeName(event){
    this.setState({
      developerName:event.target.value
    });
  }
render(){    // Using render method
  return(

      <div>        

        <h2> Simple Event Handling </h2>    

        <label htmlFor = "Name">Enter Your Name </label>
        <input type = "text" id = "devName" onChange={this.changeName.bind(this)}/>
        <h1>Hello Developer {this.state.developerName} Happy Coding </h4>

      </div>
  );
}
}
export default EventManage;
  • Related