Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to clear and select items programmatically

Tags:

reactjs

antd

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.

like image 223
Feng Xi Avatar asked Nov 21 '17 14:11

Feng Xi


People also ask

How do you clear the Select option on an ANTD?

Clear the value of the Selection field by setting it to null programmatically (e.g. via Button). The value will be set to null but the Selection field will still display the most recent selected value. Clearing the field is only possible via the allow clear user interaction button.

How do you clear selected value of dropdown in react select?

By clicking on the clear icon which is shown in DropDownList element, you can clear the selected item in DropDownList through interaction.

How do you reset the select component in react?

passing null in value attribute of the react-select will reset it.

How do you use react in select?

To select a default option in React, the selected attribute is used in the option element. In React, though, instead of using the selected attribute, the value prop is used on the root select element. So, you can set a default value by passing the value of the option in the value prop of the select input element.


1 Answers

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>
    </>
  )
}
like image 107
lmiguelvargasf Avatar answered Nov 27 '22 18:11

lmiguelvargasf