Search code examples
javascriptreactjsant-design-pro

How to Get value of select onChange in Functional Component in React


Im Using ant design pro with react to create form, but i cannot save the value of select using hooks. i Shows a errorn errorenter image description here

const ExistingGroup = (props) => {
  const [group,setGroup] = useState([]);

  const saveGroup = (event) => {
    setGroup(event.target.value);
  }
  return (
    <PageContainer header={{ title: '' }} ghost>
      <Card bordered={false} style={{ width: '100%' }}>
        <Form>
          <Form.Item>
            <Select value={group} onSelect={saveGroup}>
              <Option value='1'>1</Option>
              <Option value='2'>2</Option>
            </Select>
            {group}
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

Solution

  • If you read the documentation of Select, the onSelect method is called with the value of the selected element.

    onSelect Called when an option is selected, the params are option's value (or key) and option instance
    function(string | number | LabeledValue, option: Option)

    so you want

    const saveGroup = (value) => {
      setGroup(value);
    }
    

    Also, since it is not multiselect, you should use a single value for the group and not an array.

    const [group,setGroup] = useState(null);