javascriptcssreactjsreact-select

React-Select Custom Component Not Working With Input


I'm working on creating a custom component for React-Select that adds a button to the options.

const customSingleValue = ({ data }) => (
   <div className="custom-single-value">
      <span> {data.label} </span>
      <button>Click me</button>
   </div>
);

<Select
   className="dropdown"
   options={fruitOptions}
   components={{ SingleValue: customSingleValue }}
/>

However, I'm having trouble integrating this with React-Select's input/search feature. The button appears on a separate line, but I want it to stay on the same line as the input/search. Additionally, I want the base functionality of the custom component to be overwritten/hidden by the input/search when the user starts typing.

Not Styling With input

Question: How can I ensure my custom component stays on the same line as the input/search and is replaced by the input/search when the user starts typing, same as the default behavior?

Full Code:

import Select from "react-select";

const DropdownTest = () => {
    const fruitOptions = [
        { value: 'apple', label: 'Apple' },
        { value: 'banana', label: 'Banana' },
        { value: 'cherry', label: 'Cherry' },
        { value: 'date', label: 'Date' },
        { value: 'fig', label: 'Fig' }
    ];

    const customSingleValue = ({ data }) => (
        <div className="custom-single-value">
            <span> {data.label} </span>
            <button>Click me</button>
        </div>
    );

    return (
        <div className="dropdown-container">
            <Select
                className="dropdown"
                options={fruitOptions}
                components={{ SingleValue: customSingleValue }}
            />
        </div>
    );
};
export default DropdownTest;

Solution

  • Utilize props to pass in existing information. You can also utilize children instead of data.

    const customSingleValue = ({...props}) => (
            <components.SingleValue {...props}>
                <div className="custom-single-value">
                    {props.children}
                    {/* <span>{props.getValue()[0].label} </span> */}
                    <button>Click me</button>
                </div>
            </components.SingleValue>
        );