Unable to set value to select box in antd

Viewed 32

Unable to set Select field value through ref in antd

<Select
  allowClear
  showSearch
  placeholder="Please select"
  className="onclick_field_width"
  ref={ref}
>
  <Select.Option className="option-tab" value="Fulltime">
    Fulltime
  </Select.Option>
  <Select.Option className="option-tab" value="Internal Contractor">
    Internal Contractor
  </Select.Option>
  <Select.Option className="option-tab" value="Third Party Contractor">
    Third Party Contractor
  </Select.Option>
</Select>

using below code to get ref value but getting undefined.

<button onClick={() => handleRef()}>Clear field</button>;

const handleRef = () => {
  console.log("show ref::", ref.current.value);
};

if I use the same code with <Input/> field it works like a charm ref.current.input.value.

Please help.

1 Answers

Ant Design Select component does not bind any values to ref you pass as you expect like a native HTML element. It had only focus, blur, scrollTo functions.

To achieve what you are trying, you can use useState hook and make Select a controlled component like below:

import React, { useState } from "react";
import { Select } from "antd";

const App = () => {
  const [value, setValue] = useState("Fulltime");

  const handleChange = (value) => {
    setValue(value);
  };

  const handleClear = () => {
    setValue("");
  };

  return (
    <>
      <Select
        style={{
          width: 200
        }}
        value={value}
        onChange={handleChange}
      >
        <Select.Option className="option-tab" value="Fulltime">
          Fulltime
        </Select.Option>
        <Select.Option className="option-tab" value="Internal Contractor">
          Internal Contractor
        </Select.Option>
        <Select.Option className="option-tab" value="Third Party Contractor">
          Third Party Contractor
        </Select.Option>
      </Select>
      <button onClick={() => handleClear()}>Clear field</button>
    </>
  );
};

export default App;

Working Demo

Edit Basic Usage - antd@4.22.5 (forked)

Related