Dickens
Dickens

Reputation: 915

this inside react class component works differently

I am new to React and if I try to get access to openm2() using this.openm2() in openm method then I got error

"Cannot read property 'openm2' of undefined"

class Car extends React.Component {
  openm2() {
    return "Hello from openm2";
  }

  openm(e) {
    e.preventDefault();
    this.openm2(); Here I get error

  }

  render() {
    return (
      <div>
        <h1>
          {this.props.type.map((item, index) => {
            return <p key={index}>{item}</p>;
          })}
        </h1>
        <form onSubmit={this.openm}>
          <input type="text" name="type" />
          <button>Remo all</button>
        </form>
      </div>
    );
  }
}

Upvotes: 0

Views: 37

Answers (2)

ravibagul91
ravibagul91

Reputation: 20755

Change your openm function to arrow function, which binds this to function automatically.

openm = (e) => {
    e.preventDefault();
    this.openm2(); Here I get error
}

Or, you can bind this like,

<form onSubmit={this.openm.bind(this)}>

Or, you can bind this in constructor

constructor(props){
  super(props);
  this.openm = this.openm.bind(this)
}

Upvotes: 1

Nagesh
Nagesh

Reputation: 437

You need to bind the current this reference, so you can use the arrow function for this. please check below code

class Car extends React.Component {
  openm2 = () => {
    return "Hello from openm2";
  }

  openm = (e) => {
    e.preventDefault();
    this.openm2();     
  }

  render() {
    return (
      <div>
        <h1>
          {this.props.type.map((item, index) => {
            return <p key={index}>{item}</p>;
          })}
        </h1>
        <form onSubmit={this.openm}>
          <input type="text" name="type" />
          <button>Remo all</button>
        </form>
      </div>
    );
  }
}

Upvotes: 1

Related Questions