Search code examples
reactjsantd

how to clear and select items programmatically


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.


Solution

  • 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>
        </>
      )
    }