Search code examples
javascriptarraysreactjsredux-form

Remove specific array element, not just last one with .pop - Redux-form


https://codesandbox.io/s/qzm5q6xvx4

I've created the above codesandbox. I am using redux-form ([https://redux-form.com]) that where you can add and remove fields to populate the form using .push and .pop 2.

The problem with using .pop it only takes off the last array element, I would like the option for each .push created element to have its own "remove" button, therefore not simply taking the last item off the array.

I assume I would need to assign the .pop to look at the matching react .map element somehow?

const renderForm = ({ fields, label }) => (
  <div>
    <div
      variant="fab"
      color="primary"
      className="jr-fab-btn"
      aria-label="add"
      onClick={() => fields.push()}
    >
      ADD
    </div>
    <div
      variant="fab"
      color="primary"
      className="jr-fab-btn"
      aria-label="add"
      onClick={() => fields.pop()}
    >
      REMOVE
    </div>
    {fields.map((newIntel, index) => {
      console.log("newIntel", newIntel, index);
      return (
        <Field
          name={newIntel}
          key={index}
          label={label}
          placeholder={label}
          component={renderTextField}
          placeholder={label}
          label={label}
        />
      );
    })}
  </div>
);

Any ideas would be welcome.


Solution

  • If you will look into the fields which is a prop to your renderForm, it contains a method remove to remove a specific element. Just pass it the index. below is modified code-block of your component. I have made it class-component:

    class renderForm extends React.Component {
     render(){
      let {fields, label} = this.props;
      const removeName = (index) => {
        fields = fields.remove(index);
      }
    return(
      <div>
        <div
          variant="fab"
          color="primary"
          className="jr-fab-btn"
          aria-label="add"
          onClick={() => fields.push()}
        >
          ADD
    </div>
    
        {fields.map((newIntel, index) => {
          console.log("newIntel", newIntel, index);
          return (
            <div>
              <Field
                name={newIntel}
                key={index}
                label={label}
                placeholder={label}
                component={renderTextField}
              />
              <p
                variant="fab"
                color="primary"
                style={{'cursor': 'pointer'}}
                className="jr-fab-btn"
                aria-label="add"
                onClick={() => removeName(index)}
              >
                REMOVE
          </p>
            </div>
          );
        })}
      </div>
     )
    }}
    

    Hope, you can understand the code-block easily. Just paste the above code in place of your renderForm component. It will work like magic. :p