1

I have a react select using sortable container and the values that are extracted are like:

{
  "fruits": [
    {
       "id": 3,
       "value": "vanilla",
       "label": "Vanilla"
    },
    {
       "id": 1,
       "value": "chocolate",
       "label": "Chocolate"
    }
  ]
} 

In normal way using select I used to pass id to the select to get the initial value. How I can do that as I will get list of selected ids from backend?

For example if I have a list ss= [1,3], vanilla and chocolate should be selected.

import React from "react";
import Styles from "./Styles";
// import { render } from "react-dom";
import { Form, Field } from "react-final-form";
import arrayMutators from "final-form-arrays";
import { FieldArray } from "react-final-form-arrays";
import {
  SortableContainer,
  SortableElement,
  SortableHandle,
} from "react-sortable-hoc";
import Select from "react-select";

const options = [
  { id: 1, value: "chocolate", label: "Chocolate" },
  { id:2, value: "strawberry", label: "Strawberry" },
  { id:3, value: "vanilla", label: "Vanilla" },
];
const DragHandle = SortableHandle(() => (
  <span style={{ cursor: "move" }}>Drag</span>
));

const SortableItem = SortableElement(({ name, fields, value }) => (
  <li>
    <DragHandle />
    <Field name={`${name}.fruittName`}>
      {({ input }) => (
        <Select options={options} placeholder="Select Location" {...input} />
      )}
    </Field>
    <span onClick={() => fields.remove(value)} style={{ cursor: "pointer" }}>
      Remove
    </span>
  </li>
));

const SortableList = SortableContainer(({ items }) => {
  return (
    <ul>
      {items.map((name, index) => (
        <SortableItem
          key={`item-${index}`}
          index={index}
          value={index}
          name={name}
          fields={items}
        />
      ))}
    </ul>
  );
});

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const initialValues = {company: 'nagween', fruits: [
  {
    fruittName: {
      id: 3,
      // value: "vanilla",
      // label: "Vanilla"
    }
  }
]}

const onSubmit = async (values) => {
  console.log('values :>> ', values);
  await sleep(300);
  window.alert(JSON.stringify(values, 0, 2));
};

const sortEnd =
  (move) =>
  ({ oldIndex, newIndex }) => {
    move(oldIndex, newIndex);
  };


const Home = () => {
  return (
    <div>
      <Styles>
        <h1>React Final Form - Array Fields</h1>
        <a href="https://github.com/erikras/react-final-form#-react-final-form">
          Read Docs
        </a>
        <Form
          initialValues={initialValues}
          onSubmit={onSubmit}
          mutators={{
            ...arrayMutators,
          }}
          render={({
            handleSubmit,
            form: {
              mutators: { push, pop },
            },
            pristine,
            reset,
            submitting,
            values,
          }) => {
            return (
              <form onSubmit={handleSubmit}>
                <div>
                  <label>Company</label>
                  <Field name="company" component="input" />
                </div>

                <div className="buttons">
                  <button
                    type="button"
                    onClick={() => push("fruits", undefined)}
                  >
                    Add Customer
                  </button>
                  <button type="button" onClick={() => pop("fruits")}>
                    Remove Customer
                  </button>
                </div>
                <FieldArray name="fruits">
                  {({ fields }) => (
                    <SortableList
                      useDragHandle={true}
                      items={fields}
                      onSortEnd={sortEnd(fields.move)}
                    />
                  )}
                </FieldArray> 
                <div className="buttons">
                  <button type="submit" disabled={submitting || pristine}>
                    Submit
                  </button>
                  <button
                    type="button"
                    onClick={reset}
                    disabled={submitting || pristine}
                  >
                    Reset
                  </button>
                </div>
                <pre>{JSON.stringify(values, 0, 2)}</pre>
              </form>
            );
          }}
        />
      </Styles>
    </div>
  );
};

export default Home;
 
colinD
  • 1,641
  • 1
  • 20
  • 22
Nagween Jaffer
  • 180
  • 3
  • 13

0 Answers0