Search code examples
reactjsantd

Reactjs AntD Select - how to render values only on button click


I have an AntD select and button components.

I want the selected values in the select component to only render when the Add Item button is clicked (right now the update is triggered by onChange prop of the Select component).

Right now I cannot seem to figure out how to update values from handleUpdateValues

import React, {useState } from "react";
import { Select, Button } from "antd";
import { PlusOutlined } from '@ant-design/icons';


export const AntdSelect = () => {
    const [items, setItems] = useState([
        {
            value: "Jack",
            label: "Jack (100)",
        },
        {
            value: "Lucy",
            label: "Lucy (101)",
        },
    ]);
    const [values, setValues] = useState([]);
    const [selectedValues, setSelectedValues] = useState([]);

    const handleUpdateValues = () => {
        console.log(selectedValues);

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

    return (
        <>
            <Select
                mode="multiple"
                allowClear
                labelInValue
                style={{
                    width: 500,
                }}
                placeholder="custom dropdown render"
                onChange={handleChange}
                value={values}
                options={items}
            />
            <Button
                type="text"
                icon={<PlusOutlined />}
                onClick={handleUpdateValues}
            >
                Add item
            </Button>
        </>
    );
};


Solution

  • Your items state, needs to be an empty array initially. In the handleUpdateValues you should update the setItems with the actual array with the values.

    Edit: updated the sandbox to include your comment.

    example sandbox