I am not sure if it´s a react issue or not but I am struggling a lot with this issue. I tried to create just a simple example to post out of my project:
https://codepen.io/as3script/pen/VMbNdz?editors=1111
There are four buttons on the example.
To reproduce the problem press each of the first three buttons to create a text input from and enter a value. For example enter 100 into the first one, 200 into the second and 300 into the third. Now press the fourth button to remove the first input.
It should keep the second and third with their respective values, 200 and 300, but instead it´s showing 100 in the second and 200 in the third.
This code is the same as it is on CodePen, it just didn't allow the link to be posted without this.
class ButtonComponent extends React.Component {
constructor(props) {
super(props);
this.state = {filtersArr:[]}
this.addButtons = this.addButtons.bind(this);
this.removeButtons = this.removeButtons.bind(this);
this.getInput = this.getInput.bind(this);
this.onChangeHandler = this.onChangeHandler.bind(this);
}
addButtons(e){
let tempArr = this.state.filtersArr;
tempArr.push({comp:this.getInput(e.target.id), id:e.target.id});
this.setState({filtersArr:tempArr});
}
removeButtons(e){
console.log(e.target.id);
let newArr = this.state.filtersArr.filter((filter)=>{
return (filter.id !=='FirstButton')
})
this.setState({filtersArr:newArr});
}
onChangeHandler(e){
console.log(e.target.value);
}
getInput(id){
return (
<div>
<h6>{id}</h6>
<input
id="min"
type="text"
placeholder="min"
onChange={this.onChangeHandler}/>
</div>
)
}
render() {
let styles = {
display:'inline-block'
}
return (
<div>
<p>Add three buttons and enter the number in each input, and remove amt.</p>
<button id="FirstButton" onClick={this.addButtons}>FirstButton</button>
<button id="SecondButton" onClick={this.addButtons}>SecondButton</button>
<button id="ThirdButton" onClick={this.addButtons}>ThirdButton</button>
<button id="FirstButton" onClick={this.removeButtons}>Remove firstButton</button>
<ul>
{this.state.filtersArr.map((filter, index)=>{
return <li style={styles} key={index}>{filter.comp}</li>
})
}
</ul>
</div>
);
}
}
ReactDOM.render(
<ButtonComponent/>,
document.getElementById('root')
);