0

I am using reactjs controlled input

reference for below code

<input type="text" 
       value={this.state.username}
       onChange={(e) => this.setState({ username: e.target.value })}
       />

I want to avoid extra code like value , onChange And move them to component like

<input type="text" setValueOnChange=(this,'username')/>
vijay
  • 10,276
  • 11
  • 64
  • 79
  • Show us what you have tried first. – Chris Jul 07 '17 at 13:47
  • i don't know if on attribute level we can create component – vijay Jul 07 '17 at 13:49
  • "attribute level"? What do you mean? – Chris Jul 07 '17 at 13:50
  • I am thinking `setValueOnChange` as component. what i was able to think is create A whole New component that returns .If i create like this then if future there might be lots of attributes comming – vijay Jul 07 '17 at 13:52
  • Eg : like how in angular we create attribute level directives Eg : – vijay Jul 07 '17 at 13:52
  • why not using uncontrolled component: ` this.userName=el}/>` and to get it's value use `this.userName.value`. – Mayank Shukla Jul 07 '17 at 13:54
  • @MayankShukla according to research i did , [controlled input is having lots of benefits](https://goshakkk.name/controlled-vs-uncontrolled-inputs-react/) – vijay Jul 07 '17 at 13:57
  • so if i go with uncontrolled input i will have to write more useless code...thats what i want to manage and keep aside – vijay Jul 07 '17 at 18:40

1 Answers1

0

While getting exactly the result you want is not possible, just because it is not a syntactically valid JSX. It is possible to make something looking quite similar to that:

// in render
<input type="text" 
  value={this.state.username}
  onChange={setValue(this, 'username')}
/>

// add this method to the component
setValue(propName) {
  return (e) => {
    this.setState({ [propName]: e.target.value })
  }
}

You can actually extract the setValue function and reuse it with any other component:

// in render
<input type="text" 
  value={this.state.username}
  onChange={setValue(this, 'username')}
/>

// somewhere outside of the component
function setValue(component, propName) {
  return (e) => {
    component.setState({ [propName]: e.target.value })
  }
}

I believe I've seen some quite popular React forms handling library which was doing exactly this, but in a bit smarter way — they have cached the generated function to avoid creating a bunch of new function objects on each render. Just can't recall how was it named — there are too much new libs in the react world :)

Dmitry Sokurenko
  • 6,042
  • 4
  • 32
  • 53