1

There's something i've discovered recently but i'm not sure why it does work. I used to do this when making react components:

class App extends React.Component {
  state = {
    input: ''
  }

  onChangeHandler = event => {
    this.setState({input: event.target.value});
  }

  render() {
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <input value={this.state.input} onChange={(event) => this.onChangeHandler(event)} />
      </div>
    );
  }
}

I understand this is creating a new function each time it re-renders. So I remember reading somewhere that this also worked:

class App extends React.Component {
    state = {
      input: ''
    }

  onChangeHandler = event => {
    this.setState({ input: event.target.value });
  }

  render() {
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <input value={this.state.input} onChange={this.onChangeHandler} />
      </div>
    );
  }
}

I'm using the latter now since it doesn't create a new function for each re-render. The thing is, how does that work? How is the event getting to the handler if i'm not passing it as a parameter in the onChange prop in the input tag? I'm just passing the reference.

Sorry if this has been asked, I've had no luck searching for an answer.

Thanks!

mila
  • 11
  • 1

1 Answers1

2

When you say <input onChange={this.onChangeHandler} /> all you are doing is defining a function to be called when the onChange event is triggered. React will call this function and pass it a SyntheticEvent (more on that on the docs page here).

So all you need to do have access to the event data is to make sure whatever function you give to the onChange attribute accepts an event as its first parameter. Notice that in both your examples, you are doing exactly that.

miyu
  • 346
  • 1
  • 8
  • 1
    Oh I see, so this is something specific to React events? Because I remember seeing something similar using promises, for example: `async function sequence() { const output1 = await a(); const output2 = await b(); const output3 = await c(); return ''sequence is done" } sequence().then(console.log)` How does the console.log knows what to log if i'm not passing any parameter? Thanks! – mila Mar 22 '19 at 03:59
  • This answer should help you out! [https://stackoverflow.com/a/50836380/11240618](https://stackoverflow.com/a/50836380/11240618) – miyu Mar 22 '19 at 04:02
  • Thanks!! Appreciate it – mila Mar 22 '19 at 04:41