reactjs - Handling multiple onChange callbacks in a React component -


this how i'm handling scenario 2 input boxes. separate update method each one. can/should done single handlechange method instead?

https://codepen.io/r11na/pen/bzkopj?editors=0011

class app extends react.component {   constructor(props) {     super(props);      this.handlechange1 = this.handlechange1.bind(this);     this.handlechange2 = this.handlechange2.bind(this);      this.state = {       name1: '',       name2: ''     };   };    handlechange1(e) {     this.setstate({       name1: e.target.value     });   };    handlechange2(e) {     this.setstate({       name2: e.target.value     });   };    render() {     return (       <div class="row column">         <label name={this.state.name1}/>         <input onchange={this.handlechange1} />         <label name={this.state.name2}/>         <input onchange={this.handlechange2} />       </div>     );   }; }  const label = props => (   <p {...props}>hello: <span classname="label-name">{props.name}</span></p> );  const input = props => (   <input placeholder="enter name" {...props} type="text" />  );  reactdom.render(<app />, document.getelementbyid('app')) 

can/should done single handlechange method instead?

you can simplify code so.

class app extends react.component {   constructor(props) {     super(props);      this.state = {       name1: '',       name2: ''     };   };    handlechange(e, name) {     this.setstate({ [name]: e.target.value });   };    render() {     return (       <div class="row column">         <label name={this.state.name1}/>         <input onchange={ (e) => this.handlechange(e, 'name1') } />         <label name={this.state.name2}/>         <input onchange={ (e) => this.handlechange(e, 'name2')  } />       </div>     );   }; } 

example


thanks @alik mentioned eslint rule jsx-no-bind,

a bind call or arrow function in jsx prop create brand new function on every single render. bad performance, result in garbage collector being invoked way more necessary.

following rule can change code

class app extends react.component {   constructor(props) {     super(props);      this.onchange = {       name1: this.handlechange.bind(this, 'name1'),       name2: this.handlechange.bind(this, 'name2'),     }      this.state = {       name1: '',       name2: ''     };   };    handlechange(name, event) {     this.setstate({ [name]: event.target.value });   };     render() {     return (       <div class="row column">         <label name={this.state.name1}/>         <input onchange={ this.onchange.name1 } />         <label name={this.state.name2}/>         <input onchange={ this.onchange.name2 } />       </div>     );   }; } 

example


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -