Duc Hong
Duc Hong

Reputation: 1179

react-final-form with multiple select

I'm trying to build a form with a multiple value Select component by Material-UI using react-final-form. Somehow with single Select, I can get the value but with multiple, it doesn't. Somehow it seems like react-final-form is holding its own value internally.

Here's a the guiding link from Material-UI for building multiple Select:

https://codesandbox.io/s/sr6pf

I tried to replicate the very first example (without using react hook) in my form and I still miss something ?

https://codesandbox.io/embed/react-final-form-material-ui-example-jfmoe

What should I add to my Component to make this work ?

Thanks,

Upvotes: 1

Views: 5794

Answers (2)

ShahNewazKhan
ShahNewazKhan

Reputation: 1127

I was able to solve this with by setting the fomat as such

<Field
 name="concepts"
 component={Select}
 displayEmpty={trie}
 multiple={true}
 value={[]}
 format={value => value || []}
 />

As per https://github.com/erikras/redux-form-material-ui/issues/212#issuecomment-358376925

Upvotes: 1

Duc Hong
Duc Hong

Reputation: 1179

For some reasons I've managed to figure out the solution for my own question. The proper answer is to create a custom MultiSelect component instead of reusing the one from final-form-material-ui.

Notes: I've tried to use <Select /> from final-form-material-ui but adding multiple prop to the component will not be passed to , this is weird.

So, my custom component would look like this, almost similar to the one from their github with multiple prop added.

import React from 'react';
import FormControl from '@material-ui/core/FormControl';
import FormHelperText from '@material-ui/core/FormHelperText';
import InputLabel from '@material-ui/core/InputLabel';
import Select from '@material-ui/core/Select';

function SelectMulti({
  input: { name, value, onChange, ...restInput },
  meta,
  label,
  formControlProps,
  ...rest
}) {
  const showError =
    ((meta.submitError && !meta.dirtySinceLastSubmit) || meta.error) &&
    meta.touched;

  return (
    <FormControl {...formControlProps} error={showError}>
      <InputLabel htmlFor={name} shrink>
        {label}
      </InputLabel>
      <Select
        {...rest}
        multiple
        name={name}
        value={value}
        onChange={onChange}
        inputProps={restInput}
      />
      {showError && (
        <FormHelperText>{meta.error || meta.submitError}</FormHelperText>
      )}
    </FormControl>
  );
}

SelectMulti.propTypes = {};

export default SelectMulti;

Hope this help someone in the future

Upvotes: 2

Related Questions