0
votes

My redux form receives as a prop a list categories as follow:

[{"id": 1, "name_of_category": "foo"}, {"id": 2, "name_of_category": "bar"}]

Using this example from redux form website, I successfully built-in multiselect React Widget into my form, so a user can pick either "foo" or "bar" or both of them. My form also successfully returns a list of names of selected categories, i.e. ["foo", "bar"] on form submit.

It is all good, but to make my life easier on the back end, I want to return a list of id's of selected categories instead of the list of names.

What can I do for that matter? Do I need to introduce an additional function that will do the job? Or, there is built-in functionality in the React Widget package?

Here is code snippet of my redux form:

import React from 'react';
import Multiselect from 'react-widgets/lib/Multiselect'
import { Field, reduxForm } from 'redux-form';
import { Form, Button } from 'reactstrap';

import 'react-widgets/dist/css/react-widgets.css'

const required = value => value ? undefined : 'Required';
const renderMultiselect = ({ input, data, valueField, textField }) => 
  let categories = [];
  data.map(category => categories.push(category.name));
  return (
    <Multiselect {...input}
      onBlur={() => input.onBlur()}
      value={input.value || []}
      data={categories}
      valueField={valueField}
      textField={textField}
    />
  )
};

const MyForm = (props) => {
  const { handleSubmit, submitting, onSubmit, categories } = props;
  return (
    <Form name="myform" onSubmit={handleSubmit(onSubmit)}>      
      <div>
        <label>Categories</label>
        <Field
          name="categories"
          component={renderMultiselect}
          data={categories} />
      </div>
      <Button color="primary" type="submit" disabled={submitting}>
        Submit
      </Button>
    </Form>
  );
};

export default reduxForm({
  form: 'myform',
  enableReinitialize: true
})(MyForm);
1

1 Answers

0
votes

As per DOC:

Data Array:

provide an array of possible values for the Multiselect. If an array of objects is provided you should use the valueField and textField props, to specify which object properties comprise the value field (such as an id) and the field used to label the item.

valueField:

A valueField is required when the value prop is not itself a dataItem.

textField:

Specify which data item field to display in the Multiselect and selected item.

That means you need to specify the valueField and textField in case when format of data is:

[{}, {}, {}]

Write it like this:

data = [{"id": 1, "name_of_category": "foo"}, {"id": 2, "name_of_category": "bar"}]

<Multiselect {...input}
   onBlur={() => input.onBlur()}
   value={input.value || []}
   data={data}                        //data will be same data not the name of categories
   valueField="id"                    //value will be id
   textField="name_of_category"       //text will be name of category
/>