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')/>
8
  • Show us what you have tried first. Commented Jul 7, 2017 at 13:47
  • i don't know if on attribute level we can create component Commented Jul 7, 2017 at 13:49
  • "attribute level"? What do you mean? Commented Jul 7, 2017 at 13:50
  • I am thinking setValueOnChange as component. what i was able to think is create A whole New component that returns <customInput></customInput>.If i create like this then if future there might be lots of attributes comming Commented Jul 7, 2017 at 13:52
  • Eg : like how in angular we create attribute level directives Eg : <input customValidation/> Commented Jul 7, 2017 at 13:52

1 Answer 1

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.