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?
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.
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.
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 }}
/>
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 }} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With