Search code examples
reactjscomponentsjsx

onChange react event calls function with parameters but no arguments passed?


I'm not really clear on what to title this question. My question is a more basic understanding level then an actual problem. I'm new to react. I don't understand this component function below on the line:

<input type='text' name='myinput' value={this.state.input} onChange = {this.handleChange.bind(this)} />

this handleChange function that is called has an event parameter but what is the event? Is event more of just a react key word then an actual argument passed? I do not understand?

Full component:

class ControlledInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: ""
    };
    // change code below this line
    this.handleChange = this.handleChange.bind(this);
    // change code above this line
  }
  // change code below this line
  handleChange(event) {
    this.setState({
      input: event.target.value
    });
  }
  // change code above this line
  render() {
    return (
      <div>
        {/* change code below this line */}
        <input
          type="text"
          name="myinput"
          value={this.state.input}
          onChange={this.handleChange.bind(this)}
        />
        {/* change code above this line */}
        <h4>Controlled Input:</h4>
        <p>{this.state.input}</p>
      </div>
    );
  }
}

I guess if anyone out there can break down how this works for me? Logically I do not get it?


Solution

  • The event you're receiving in the onChange function is just the native event sent by the browser when te change happens.

    It is basically an object that holds some information about the thing that just happened. In this case the target property holds the the <input /> element. So accessing event.target.value will give you the value of the input element.

    Furthermore it holds other data/functions that you can use to manipulate how the browser handles what happens. For example, you could use preventDefault() to block the default behaviour that might occur when the event is dispatched. Like when you're submitting a form you might want to stop the default behaviour from happening to handle the submit logic yourself.

    You can read more about the Event interface here: https://developer.mozilla.org/en-US/docs/Web/API/Event

    And about specifically the change event: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event


    Also, in the constructor you're already binding this to the function, so you don't have to do it again. onChange={this.handleChange} should work just fine.