Search code examples
javascriptreactjssemantic-ui-react

Custom Control Field does not render <select> options


I'm trying to implement Field with Custom Control strictly following official tutorial. But, despite my code is pretty close to original, it renders empty <select> element with options attribute equal to [object Object],[object Object],[object Object] instead of rendering dropdown menu populated with my options:

const { useState } = React,
      { render } = ReactDOM,
      { Form } = semanticUIReact

const InputsBlock = () => {
  const selectOptions = [
          {key: 'option1', text: 'Option 1', value: 'Option 1'},
          {key: 'option2', text: 'Option 2', value: 'Option 2'},
          {key: 'option3', text: 'Option 3', value: 'Option 3'}
        ],
        fields = [
          {label: 'Param 1', key: 'param1', control: 'Input'},
          {label: 'Param 2', key: 'param2', control: 'Input'},
          {label: 'Param 3', key: 'param3', control: 'Select', options: selectOptions}
        ]

  return (
    <Form.Group widths="equal">
      {
        fields.map(({control,label,key,options}) => (
          <Form.Group inline>
            <Form.Field {...{key,control,label,...(control=='Select' && {options})}} />
          </Form.Group>
        ))
      }
    </Form.Group>
  )
}

const MyForm = () => {
  return (
    <Form>
      <InputsBlock />
    </Form>
  )  
}

render (
  <MyForm />,
  document.getElementById('root')
)
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.css" /><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui-react/0.88.2/semantic-ui-react.min.js"></script><div id="root" style="margin:20px"></div>


Solution

  • In your fields array, control is not a string. Instead it should be the actual semantic-ui-react component.

    Change "fields" to below -

    import { Form, Select, Input } from "semantic-ui-react";
    
    fields = [
      { label: "Param 1", key: "param1", control: Input },
      { label: "Param 2", key: "param2", control: Input },
      {
        label: "Param 3",
        key: "param3",
        control: Select,
        options: selectOptions
      }
    ];
    

    Here is a working code of the same - https://codesandbox.io/s/optimistic-haslett-glvkf