Search code examples
react-selectreact-final-form

How can I get an array of strings as the submitted value for react-final-form using react-select?


I'm trying to get a react-select's multi-select component to submit the selected values as an array of strings but it's coming out as an array of {label, value} objects.

The structure of the objects I will be passing into react-select via react-final-form's Field component is like this:

[
{ val: "first-value", display: "First Value" }, 
{ val: "second-value", display: "Second Value" }, 
{val: "third-value", display: "Third Value"
];

Passing the prop getOptionLabel={option => option.display} is able to change the option labels to the display key given by the objects.

However doing the same thing for getOptionValue still gives me the entire {val, display} object when submitted. e.g. selecting the first item and submitting the form would get me [{val: "first-value", display: "First Value" }] when I only want ["first-value"]

I'm not too sure if it's something I need to solve on react-final-form or on react-select

import React from "react";
import { Field } from "react-final-form";
import { Form } from "react-final-form";
import Select from "react-select";

const data = [{ val: "1", display: "123" }, { val: "2", display: "321" }];
const Test2: React.FC<any> = () => {
  return (
    <Form
      onSubmit={values => console.log(values)}
      showErrorModal={showErrorModal}
      setShowErrorModal={setShowErrorModal}
    >
      {() => (
        <>
          <Field
            name="test"
            component={MultiSelect}
            label={"Multi Select test"}
            placeholder="Please Select..."
            options={data}
            getOptionLabel={option => `${option.display}`}
            getOptionValue={option => `${option.val}`}
          />
          <SubmitButton btnTxt="next" />
        </>
      )}
    </Form>
  );
};

export default Test2;

When submitting, the message I get on the console is

[{"val": "1", "display": "123"}, {"val": "2", "display": "321"}]

whereas the result I'm hoping for is ["1","2"]


Solution

  • getOptionLabel & getOptionValue are only for viewing purpose.

    When we get the selected value, it will give you the complete object as we provided array of object to options.

    So the result of,

    onSubmit={values => console.log(values)}
    

    is correct, which is [{"val": "1", "display": "123"}, {"val": "2", "display": "321"}]

    You need to further work on this result to get your desired result as,

    onSubmit={values => console.log(values.map(data=>data.val))}