user8227859
user8227859

Reputation: 65

React Components utilization

I am trying to use the following component in my file, but cannot format options as the component would like. New to this... any ideas on how to fix my code would be greatly appreciated. Field below the componenet is how I'm trying to use it.

/**
* Single select dropdown component
* - Uses an array passed to options prop
* - 'options' Array must have 'value' (what is submitted) & 'text' 
(what is displayed)
*/
export class SingleSelect extends React.Component {
render () {
    const {
        input,
        label,
        options,
        required,
        placeholder,
        meta: { error, warning, touched },
        ...props
    } = this.props;

    let message;
    const validationState = touched && ( error && 'error' ) || ( warning && 'warning' ) || null;

    if ( touched && ( error || warning ) ) {
        message = <span className="help-block">{ error || warning }</span>;
    }

    let placeholderText = 'Select an option';
    if ( placeholder ) {
        placeholderText = placeholder;
    }

    const asterisk = required && (<span className="form-field-required" />) || null;

    return (
        <FormGroup validationState={ validationState }>
            <ControlLabel>
                { label }
                { asterisk }
            </ControlLabel>

            <FormControl {...{
                ...input,
                componentClass: 'select',
                placeholder: placeholderText,
                ...props
            }} >
                <option value="">{ placeholderText }</option>
                {
                    options.map((option, index) => (
                        <option key={index} value={option.value}>
                            {option.text}
                        </option>
                    ))
                }
            </FormControl>
            { message }
            <FormControl.Feedback />
        </FormGroup>
    );
}
}

<Field
 name="type"
 label="Type"
 component={fields.SingleSelect}
  options={
     text=[Media File, External File]
     value=type
  }
  required
  placeholder
  validate={[validators.required]}
 />

Upvotes: 0

Views: 40

Answers (1)

Chase DeAnda
Chase DeAnda

Reputation: 16451

You need extra {} around the object you are passing:

<Field
  name="type"
  label="Type"
  component={fields.SingleSelect}
  options={[{
     text: 'Media File'
     value: type
  },{
     text: 'External File'
     value: type
  }]}
  required
  placeholder
  validate={[validators.required]}
/>

In JSX, the first {} indicate that what's inside is JavaScript that needs to be ran. So you can kind of think about the first {} being ignored.

Upvotes: 2

Related Questions