Triyugi Narayan Mani
Triyugi Narayan Mani

Reputation: 3109

How to remove value from array using index (Ant Design specific)?

I am creating a questionnaire type form using ReactJs and Ant Design. It is a follow up question of How to create a questionnaire type form using Ant Design?

Now I am succeeded in adding new questions and their respective answers but not in removing them. Let's suppose I have added three questions and when I am trying to remove any one of them, its always removing the last one. The related code for removing is as follows:

remove = k => {
    console.log(k);
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue("keys");
    // We need at least one passenger
    if (keys.length === 1) {
      return;
    }
    keys.splice(k, 1);
    // can use data-binding to set
    form.setFieldsValue({
      keys: keys
    });
    console.log(keys);
  };

The complete code can be found as a demo on codesandbox.io.

Upvotes: 2

Views: 1809

Answers (2)

Victor Orlyk
Victor Orlyk

Reputation: 1843

You should be able to get FormListOperation and then just

 <Form.List name={listName}>
        {(fields, operation) => {
...
operation.remove(index)

Upvotes: 0

karolis2017
karolis2017

Reputation: 2415

I have done something similar in the past. Got rid of the boilerplate of antd's remove and replaced with this. Every time I add a row I push that row (object) to formRows array then removing like this:

  remove = key => {
    const newRows = this.state.formRows.filter(r => r.key !== key)
    this.setState(
      prev => ({
        formRows: newRows
      })
    )
  }

Upvotes: 1

Related Questions