'React input elements rendering in wrong order on state change
I have a list of inputs with an empty input at the end.
If a user types in this empty input, the state is changed to reflect this, and a new blank input is added to the end.
If the user deletes the value in the input at the end (not the blank one), this input is removed and we still have a blank input at the end.
The issue: There are at least 4 inputs (first 3 with values, last blank as expected). The user makes input 2 blank.
Expected result: Inputs are re-rendered in the new order (Input1, Input3, BlankInput)
Actual result: Inputs rendered in this order (Input 1, BlankInput, Input3)
Code:
type Props = {}
const InitialState = {
data: [],
}
type State = typeof InitialState
export default class List extends React.Component<Props, State> {
public state = InitialState
componentDidMount() {
var inputs = [];
//Call API to get data
getList().then((dataArray) => {
inputs = JSON.parse(dataArray)
this.setState({ data: inputs })
});
}
generateInput(input: any) {
var listArray = input.config.order.split(',');
listArray.push('');
return listArray;
}
delaySaveOfList(e: React.ChangeEvent<any>, input: any, name: string) {
var listArray = input.config.order.split(',')
var arrTarget = Number(e.target.name);
var inputLength = e.target.parentElement.querySelectorAll("#ListInput").length - 1
if (e.target.value == "" && inputLength > 1) {
var newInputArray = [] as any;
this.state.data.forEach((inputState: any) => {
if (inputState === input) {
listArray.splice(arrTarget, 1);
input.config.order = listArray.toString();
newInputArray.push(input)
}
else {
newInputArray.push(inputState)
}
})
this.setState({ data: newInputArray })
//Save this new list to API
updateList(input);
}
}
onChange(e: React.ChangeEvent<any>, input: any, name: string) {
e.persist();
if (e.target.refreshTimer) {
clearTimeout(e.target.refreshTimer);
}
e.target.refreshTimer = setTimeout(() => {
this.delaySaveOfList(e, input, name)
}, 1000);
};
render() {
return (
<div>
<h1>Inputs</h1>
{this.state.data.map((input: any) => (
<div className="card">
<div className="card-body">
<p className="card-text">Inputs:</p>
{this.generateInput(input).map((name: any, index: number) => (
<>
<input id="ListInput" type="text" defaultValue={name} name={index.toString()} key={index} onChange={(e) => { this.onChange(e, input, name) }} />
<br />
</>
))}
</div>
</div>
))}
</div>
)
}
}
I will say, once I refresh the page, the order of the inputs is correct, as it pulls data from the API again, so I assume I'm doing something wrong with the state data.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|