1

I am new to React and learning click events. But the issue I faced is that one button click I get "Cannot GET /[object%20Object]". Here is the code I am using:

class Engine extends React.Component {
  render() {
    let types = ["Diesel", "Gazoline"];
    return (
      <div>
        <Car type={types} />
      </div>
    );
  }
}

class Car extends React.Component {
  open() {
    console.log("You have clicked");
  }
  render() {

    return (
      <div>
        <h1>
          {this.props.type.map((item, index) => {
            return <p key={index}>{item}</p>;
          })}
        </h1>
        <button onClick={open}>Remove all</button>
      </div>
    );
  }
}

const box = document.querySelector(".mir");

ReactDOM.render(<Engine />, box);
Dickens
  • 895
  • 3
  • 11
  • 25

2 Answers2

2

You need to use this.open, since it doesn't know exactly what you're referring to by open :

<button onClick={this.open}>Remove all</button>

If you were to have named the function, say, foo instead of open, then it wouldn’t have worked at all.

The reason why you're seeing the functionality is because it is using the default open command built into JavaScript, which opens a new page. Under the hood, clicking the button is calling open(e) where e is the button event. So it's trying to open a new page, but instead of it receiving a URL, it's receiving an object, and thus you're seeing the error you received.

Instead, you want to use the open that is defined in the class. In order to do that, you need to use this.open.

In addition, if you want to pass something to the function as an argument, you'll need to change it a bit.

You can change open to:

open = (myparam) => {
    console.log("You have clicked");
    console.log(myparam);
}

In order to bind this. Then you can do something like:

<button onClick={_ => this.open("foo")}>Remove all</button>
rb612
  • 5,280
  • 3
  • 30
  • 68
1

You need to bind the open function to component and also call it with 'this'. Or you can make the arrow function.

<button onClick={this.open.bind(this)}

or

open = () => { ... }
<button onClick={this.open}
freedev111
  • 132
  • 4