6

So I've recently discovered that callbacks for event handlers are bad for rendering performance: https://reactjs.org/docs/handling-events.html

I'm trying to heed this by grabbing the properties off the event in a class method rather than doing something like: onClick={({value}) => this.setState({"someProperty" as keyof State: value})} etc.

However now that I can't explicitly declare typesafety in that callback, I'm trying to be dynamic about it and my typechecker is okay with the code below, but how can I make it complain about the input element having a name attribute that is not a keyof State?

interface State {
  someProperty: string;
}

class MakeMeSafer extends React.Component<{}, State> {

  state: State = {
    someProperty: ''
  }

  set = ({ currentTarget: { name, value } }: React.SyntheticEvent<HTMLInputElement>): void => {
    this.setState({ [name as keyof State]: value });
  }

  render(): JSX.Element {
    return (
      <div>
        <input type="text" name="some-name-not-in-state" onChange={this.set} />
      </div>
    );
  }

}
xy2
  • 6,040
  • 3
  • 14
  • 34
typeofChris
  • 63
  • 1
  • 6

1 Answers1

5

You are explicitly casting your name property as a key of State, so it is normal that the compiler does not complain.

If you need type safety I would use a closure instead:

interface State {
  someProperty: string;
}

class MakeMeSafer extends React.Component<{}, State> {

  state: State = {
    someProperty: ''
  }

  onChange = (name: keyof State) =>
    (e: React.FormEvent<HTMLInputElement>) => {
      const newValue = e.currentTarget.value;
      this.setState({name: newValue});
    }
  }

  render(): JSX.Element {
    return (
      <div>
        <input type="text" onChange={this.onChange('some-name-not-in-state')} />
      </div>
    );
  }
}
klugjo
  • 19,422
  • 8
  • 57
  • 75
  • It's better to just pass `this.onChange` without calling it and adding a name prop so the closure can sit in the child. Now the function is executed every render and with this change it will only be called on the change event. – ThaJay Nov 06 '20 at 13:30