DEV Community

Discussion on: Fast & easy... React states management in one function

Collapse
 
maciejsimka profile image
Maciej Simka • Edited

using curried function is a good idea! it's very useful for handling multiple similar state changes.
another approach, if you're dealing with form elements like inputs etc. would be to use name attribute, something like this:

state = {
  firstName: '',
  message: '',
}

handleValueChange = e => {
  this.setState(() => ({ [e.target.name]: e.target.value }));
}

render() {
  return (
    <form>
      <input
        type="text"
        name="firstName"
        value={this.state.firstName}
        onChange={this.handleValueChange}
      />
      <input
        type="text"
        name="message"
        value={this.state.message}
        onChange={this.handleValueChange}
       />
    </form>
  )
}
Enter fullscreen mode Exit fullscreen mode

but of course it works only with certain html elements (<input>, <select>, <textarea> among them) and IIRC specification says name should be lowercase, although I don't think I've run into any problems with camelCase name so far.

Collapse
 
patroza profile image
Patrick Roza

I like this, how about leveraging a data- attribute instead of name?