News for hackers. Stuff that matters.
Re:JavaScript fundamentals before learning React by coltonv on Friday July 20, 2018 @12:06AM (#17572374)
This is great, and a strategy I used a lot in my last code base. If you do this for statically typed JS though, you'll get either error messages or bad typing with lots of `any`s and weak type checks.

Here's a great strategy to do the same thing with strong static types, like in flow and typescript:

  setTextField = (name: 'name' | 'email' | 'phone') => (event: InputEvent) => {
    this.setState({ user: { ...this.state.user, [name]: event.target.value } });
  }
  
  setBooleanField = (name: 'isCool') => (event: InputEvent) => {
    this.setState({ user: { ...this.state.user, [name]: event.target.checked } });
  }
  
  render() {
    <div>
    	<input type="text" onChange={ this.setTextField('email')} placeholder="Email" value={this.state.user.email} />
    	<input type="checkbox" onChange={ this.setBooleanField('isCool')} checked={this.state.user.isCool} />
    </div>
  }

More verbose than the non-typed version, but simpler than declaring a function for every field with all the goodness of strong static typing.

There are no comments on this comment yet.