using reactjs:
i have container 6 rows. each row has product name , input text field. if enter quantity input text field , sort list (ie a-z, or z-a) input text fields cleared. i've created example of problem on codepen.
how can sort rows , have input text fields keep value?
https://codepen.io/_d_v_/pen/brxqqq
class row extends react.component { constructor(props) { super(props); this.state = { inputvalue: '' } } handleinputchange(e) { this.setstate({ inputvalue: e.target.value }); } render() { return (<div classname='row'> <span classname='product-name'>{this.props.placeholder}</span> <input type='text' classname='row__input-field' value={this.state.inputvalue} onchange={ e => this.handleinputchange(e) } /> </div>); } } class container extends react.component { constructor(props) { super(props); this.state = {products: [{name: 'orange'}, {name: 'lemon'}, {name: 'apple'}, {name: 'pear'}, {name: 'banana'}, {name: 'tangerine'}, {name: 'lime'}]}; } handleselect(e) { const sorteddata = getsorteddatabyindextype(this.state.products, number(e.target.value)); this.setstate({ products: sorteddata }) } render() { return (<div classname='row-container'> <select classname='sort' onchange={e => this.handleselect(e)}> <option value="" selected disabled>sort list options</option> <option value='1'>a-z</option> <option value='2'>z-a</option> </select> { this.state.products.map((product, index) => { return <row key={ math.random() } placeholder={this.state.products[index].name} /> }) } </div>); } } const sortarraybykey = (products, key) => { products.sort((a, b) => { // ignore upper , lowercase; let valuea = a[key].touppercase(); let valueb = b[key].touppercase(); if (valuea < valueb) { return -1; } if (valuea > valueb) { return 1; } return 0; }); return products; }; const getsorteddatabyindextype = (products, sortkey) => { switch (sortkey) { case 1: products = sortarraybykey(products, 'name'); break; case 2: products = sortarraybykey(products, 'name'); products.reverse(); break; default: console.log('sort value not handled'); break; } return products; }; reactdom.render(<container />,document.getelementbyid('container'));
by keeping same key
of row
element on every render keep state of corresponding element safe. change
this.state.products.map((product, index) => { return <row key={ math.random() } placeholder={this.state.products[index].name} /> })
to this
this.state.products.map((product, index) => { return <row key={ this.state.products[index].name } placeholder={this.state.products[index].name} /> })
Comments
Post a Comment