Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a button at the end of options in react-select

I am using react-select library to implement search and select functionality in my project.

As a basic usage, I can only select the options returned after the search. It looks like this whose code is:

<AsyncSelect
       onChange={(item) => _selectedItemChange(item)}
       loadOptions={loadItemOptions}
       placeholder='Start typing'
 />

Now, I want a button at the lower end of the select box so that I can do like 'Not found? Add New' type of stuff. Something like this. I also want that button's onClick function to be my own.

How can I do this?

like image 236
Bhuwan Adhikari Avatar asked Jun 28 '20 10:06

Bhuwan Adhikari


People also ask

How do you get the button value on a click in React?

To get the value of an input on button click in React: Create a state variable to store the value of the input field. Set an onChange event handler on the input to update the state variable when the input field value changes. Set an onClick event handler on a button element.

How do you make button disappear after clicking React?

If you want to hide it permanently for a user then you have to register that user activity somewhere in the backend. Then send a http request so you can get data if the user can perform that activity again or not. Depending in the response you set some state and then from that state you can hide/show the button.


2 Answers

From the answer of @PasVV, I was able to make something, I have wanted to. By passing props to the AsyncSelect Component, we can make our own custom Menu(Customizable component in react-select) as follows.

const CustomMenu = ({ innerRef, innerProps, isDisabled, children }) =>
        !isDisabled ? (
            <div ref={innerRef} {...innerProps} className="customReactSelectMenu">
                {children}
                <button
                    className="btn btn-info btn-sm btn-block"
                    onClick={() => ...}
                >Add New</button>
            </div>
        ) : null;

And passing it to <AsyncSelect/>

<AsyncSelect
        onChange={_change}
        loadOptions={loadVendorOptions}
        placeholder='Start typing'
        components={{ Menu: CustomMenu }}
/>
like image 151
Bhuwan Adhikari Avatar answered Sep 23 '22 13:09

Bhuwan Adhikari


import { components } from 'react-select';

const SelectMenuButton = (props) => {
    return (
        <components.MenuList  {...props}>
            {props.children}
            <button>Add new element</button>
        </components.MenuList >
    ) }

<Select   components={{ MenuList: SelectMenuButton }} />
like image 44
Anthony Cifuentes Avatar answered Sep 20 '22 13:09

Anthony Cifuentes