Answer the question
In order to leave comments, you need to log in
Why is the last element removed from the array in state?
Good afternoon! There are two components, one of which has a button that calls the second component on click. The component can be called multiple times, so it's in the state array. Inside the second component there is a delete button. But when pressed, it is not the selected element that is removed, but the last one in the array. Why is this happening?
First component:
import React from 'react'
import { AnswerInput } from '../AnswerInput/AnswerInput'
class QuestionInput extends React.Component {
state = {
answers: []
}
removeAnswerHandler = index => {
this.state.answers.splice(index, 1)
this.setState({
answers: this.state.answers
})
}
addAnswerInputHandler = () => {
this.setState({
answers: [
...this.state.answers,
<AnswerInput removeAnswerHandler={this.removeAnswerHandler} />
]
})
}
render() {
return (
<div>
{this.state.answers.map((item, index) => (
<div key={index}>{item}</div>
))}
<div className="mt-3 mb-3 ml-2">
<p className="link text-secondary">
<i
className="fas fa-plus"
onClick={() => this.addAnswerInputHandler()}
/>
</p>
</div>
</div>
)
}
}
export default QuestionInput
import React from 'react'
import { Input } from 'reactstrap'
export class AnswerInput extends React.Component {
render() {
return (
<div className="d-flex align-items-center">
<Input
className="answerinput"
placeholder="Ответ клиента"
defaultValue=""
/>
<i
className="far fa-trash-alt link ml-2 mr-2 text-secondary"
onClick={index => {
this.props.removeAnswerHandler(index)
}}
/>
<i className="far link ml-2 mr-2 fa-copy text-secondary" />
</div>
)
}
}
Answer the question
In order to leave comments, you need to log in
what is removed is not what you wanted, because you are not passing that index anywhere. the event handler receives the event object as a parameter, so your onClick={index => {
index does not come there at all.
and why the last one - I can’t imagine, it seems to be the first one.
either way, you're doing something wrong. there is no need to store components with input fields in an array. you probably somehow are going to receive values from there? store the entered values in the array, remake your second component into a functional one, and in the main component map those values and indices onto it.
The problem is in key. You are using an index and of course it moves out when cutting elements in the middle. Read about what it is for and how it works in the react documentation.
Solution: store in state not components but some unique numbers for each audio input, use these unique numbers as a key
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question