21

I'm using https://ant.design/components/select/

How can I programmatically remove the selected items from <Select>?
Note: the <Option> is not a string value, but a Node.

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
Feng Xi
  • 1,005
  • 2
  • 11
  • 30

9 Answers9

15

If you are using React Hooks, use the following:

import React, { useState } from 'react'
import { Button, Select } from 'antd'

const { Option } = Select

// inside your component
const ComponentName = () => {
  const [selected, setSelected] = useState()

  // handler
  const clearSelected = () => {
    // this line will clear the select
    // when you click on the button
    setSelected(null)
  }

  // in the return value
  return (
    <>
      // ...
      // In the select element
      <Select style={{ width: 150 }} onChange={value => setSelected(value)} 
        value={selected}>
        <Option value="jack">Jack</Option>
        <Option value="lucy">Lucy</Option>
      </Select>
      <Button onClick={clearSelected}>Clear Selected</Button>
    </>
  )
}
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
  • Overload 1 of 2, '(props: Readonly>): Select', gave the following error. Type 'null' is not assignable to type 'string | number | ReactText[] | LabeledValue | LabeledValue[] | undefined'. – Sytham Jul 16 '20 at 10:18
  • also setting it to undefined instead of null doesn't work either – Sytham Jul 16 '20 at 10:18
7

Just set value to null. e.g.

<Select value={null} />
coderek
  • 1,860
  • 14
  • 20
4

Try this

    class Banana extends React.Component {
          constructor() {
            super();
            this.state = {
        selected: []
};

            this.handleChange = this.handleChange.bind(this);
            this.clearSelected = this.clearSelected.bind(this);
          }

          handleChange(value) {
            this.setState({ selected: value });
          }

          clearSelected() {
            this.setState({ selected: []});
          }

          render() {
            return (
              <div>
                <Select value={this.state.selected} style={{ width: 120 }} onChange={this.handleChange} placeholder="Select option">
                  <Option value="jack">Jack</Option>
                  <Option value="lucy">Lucy</Option>
                  <Option value="disabled" disabled>Disabled</Option>
                  <Option value="Yiminghe">yiminghe</Option>
                </Select>
                <Button onClick={this.clearSelected}>clear selected</Button>
              </div>
            );
          }
        }
2

Assigning the value of Select to state should work. Try something like this:

class Banana extends React.Component {
  constructor() {
    super();
    this.state = {};

    this.handleChange = this.handleChange.bind(this);
    this.clearSelected = this.clearSelected.bind(this);
  }

  handleChange(value) {
    this.setState({ selected: value });
  }

  clearSelected() {
    this.setState({ selected: null });
  }

  render() {
    return (
      <div>
        <Select value={this.state.selected} style={{ width: 120 }} onChange={this.handleChange}>
          <Option value="jack">Jack</Option>
          <Option value="lucy">Lucy</Option>
          <Option value="disabled" disabled>Disabled</Option>
          <Option value="Yiminghe">yiminghe</Option>
        </Select>
        <Button onClick={this.clearSelected}>clear selected</Button>
      </div>
    );
  }
}

https://codepen.io/anon/pen/NwYdEx?editors=0010

Max
  • 1,517
  • 9
  • 16
  • Thanks, Max. I'm using similar code with some differences: 1. The – Feng Xi Nov 22 '17 at 06:47
1

Use undefined for the placeholder text to appear. It will not appear with null.

In this case, when selectValue variable is set to 0, null, undefined, false, the Select value is clearead.


      <Select onChange={e => setSelected(e)} 
        value={selectValue || undefined}>
        <Option value="1">Apple</Option>
        <Option value="2">Orange</Option>
      </Select>
kubiak
  • 25
  • 3
0

Without using State. Code was taken from the library itself (_this.onClearSelection in Select.js).

class MySelection extends React.Component {
      constructor() {
        this.handleChange = this.handleChange.bind(this);
        this.clearSelected = this.clearSelection.bind(this);
      }

      handleChange(value) {
        this.setState({ selected: value });
      }

      clearSelection() {
        const _this = this.refs.mySelection.rcSelect;
        const props = _this.props;
        const state = _this.state;

        if (props.disabled) {
          return;
        }

        let inputValue = state.inputValue;
        let value = state.value;

        if (inputValue || value.length) {
          if (value.length) {
            _this.fireChange([]);
          }

          _this.setOpenState(false, {
            needFocus: true
          });

          if (inputValue) {
            _this.setInputValue("");
          }
        }
      }

      render() {
        return (
          <div>
            <Select ref="mySelection" onChange={this.handleChange} placeholder="Select option">
              <Option value="jack">Jack</Option>
              <Option value="lucy">Lucy</Option>
            </Select>
            <Button onClick={this.clearSelection}>clear selected</Button>
          </div>
        );
      }
    }
Ahmad Hafiz
  • 358
  • 2
  • 6
  • 13
0

In antd, In Class Component, Using Ref, Clear or reset select list value or form item value

https://stackoverflow.com/a/64077769/11844605

Lalit Garghate
  • 119
  • 1
  • 5
0

The question is about antd. All the answers below are normal react way to clear select.

But antd is much powerful and offers useForm ref which can be used to clear form values.

You need to wrap your select within Form.Item and give it a name.

import React, { useState } from 'react'
import { Button, Select } from 'antd'

const { Option } = Select

const ComponentName = () => {

  // using this for the form reference
  const [form] = Form.useForm();

  // handler
  const clearSelected = () => {
  // mySelect is the Form.Item name select below in the html  
    form.setFieldValue('mySelect', undefined);
  }

  const onFinish = (values) => {
    console.log(values)
  }

  // in the return value
  return (
    <>
      <Form form={form} initialValues={{mySelect: 'jack'}} onFinish={onFinish}>
        <Form.Item name="mySelect">
          <Select>
            <Option value="jack">Jack</Option>
            <Option value="lucy">Lucy</Option>
          </Select>
        </Form.Item>

        <Button onClick={clearSelected}>Clear Selected</Button>

        <Form.Item>
          <Button htmlType="submit" type="primary" loading={loading}>
             Submit
          </Button>
        </Form.Item>
      </Form>
    </>
  )
}

Also with antd, you don't need to hold any state variables for holding the form values. Just wrap all antd Components within Form.Item and give a name. When the form is submitted, you'll get all the name-value pairs in the onFinish callback.

Drunken Daddy
  • 7,326
  • 14
  • 70
  • 104
0

TL;DR You only need onClear and allowClear props from Antd Select. NO need for (complicated) workaround.

For antd: 4.6.0 and up, there is a onClear prop in the select component. We will also use allowClear prop to only show the clear button when a value is present (true will be enough but change according to your usage).

According to the Documentation

allowClear: Show clear button

onClear: Called when clear

import React from "react";
import "antd/dist/antd.css";
import { Select } from "antd";

const { Option } = Select;

const handleChange = (value) => {
  // NOTE: Handle null checking when value is
  // undefined when option is cleared
  console.log(`selected ${value}`);
};

const handleClear = () => {
  console.log("cleared value");
};

const App = () => (
  <>
    <Select
      placeholder="No Option Selected"
      defaultValue={"lucy"}
      onChange={handleChange}
      onClear={handleClear} // Add this
      allowClear={true} // Add this
    >
      <Option value="jack">Jack</Option>
      <Option value="lucy">Lucy</Option>
      <Option value="Yiminghe">yiminghe</Option>
    </Select>
  </>
);

export default App;

If you want to try it out, here is the codesanbox

PrynsTag
  • 191
  • 1
  • 10