Home > Software engineering >  Convert react form component into typescript
Convert react form component into typescript

Time:06-27

I have a react form component , it is working in JavaScript perfectly, I would like to convert it into TypeScript but I get this error: Property '_title' does not exist on type 'FormComp'. The component is like:

class FormComp extends React.Component<{}> {
  constructor(props: any) {
  super(props);
  this.state = {};
 }
 handleCreate(event: any) {
   event.preventDefault();

   var title = this._title.value;
   const temp = { title: title };
   // This temp object will be send to backend by ajax call 
   .
   . 
   .
   }
   render() {
     return (
      <div className="col-md-12">
       <input
       type="text"
       className="col-sm-3 form-control"
       placeholder="Title"
       ref={(c) => (this._title = c)}
       ></input>
       <button
         className="btn btn-primary"
         onClick={this.handleCreate.bind(this)}
       >
        Create
      </button>
        );
      }
     }
        

How can I convert this component into TypeScript component ?

CodePudding user response:

Since you're using this._title, you have to define it for TypeScript. To do that:

class FormComp extends React.Component<{}> {
  _title: string; // or other type
  constructor(props: any) {
    super(props);
    this.state = {};
  }
  ...
}
  • Related