How to get value from Select/Option component from Ant design

Tesuji picture Tesuji · Apr 22, 2019 · Viewed 11.9k times · Source

I want to retrieve the value from my selection so I can make post requests. I have no problem getting from text input, but for some reason I can't get it from the drop down menu select. I end up getting a "TypeError: Cannot read property 'value' of undefined"

Here is the code I am using.

import React from "react";
import { Form, Input, Button, Select } from "antd";

const { Option } = Select;

class ItemForm extends React.Component {

  handleFormSubmit = event => {
    event.preventDefault();
    const name = event.target.elements.name.value;
    const description = event.target.elements.description.value;
    const category = event.target.elements.category.value;
    console.log(name, description, this.refs.category.value);
  };

  render() {
    return (
      <div>
        <Form onSubmit={this.handleFormSubmit}>
          <Form.Item label="Form Layout" />
          <Form.Item label="Product Name">
            <Input name="name" placeholder="Ex: Organic Apple..." />
          </Form.Item>
          <Form.Item label="Description">
            <Input name="description" placeholder="Ex: Juicy organic apples!" />
          </Form.Item>
          <Form.Item label="Category">
            <Select name="category" placeholder="Please select a category">
              <Option value="Fruit">Fruit</Option>
              <Option value="Vegetable">Vegetable</Option>
              <Option value="Poultry">Poultry</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}
export default ItemForm;

Answer

Junius L. picture Junius L. · Apr 22, 2019

Use onChange which is fired when the value of the select changes. antd select documentation

<Form.Item label="Category">
  <Select 
    onChange={(value) => {
      alert(value)
    }} 
    name="category" 
    placeholder="Please select a category">
      <Option value="Fruit">Fruit</Option>
      <Option value="Vegetable">Vegetable</Option>
      <Option value="Poultry">Poultry</Option>
  </Select>
</Form.Item>

working example