Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-select Render custom component as SingleValue

Tags:

react-select

I need to display an icon before the selected value using react-select and typescript.

This is what I tried so far:

SingleValue: React.SFC<SingleValueProps<OptionType>> = ({ children, ...props }) => (
    <components.SingleValue {...props}>
      <i className={`fal fa-${this.props.icon} has-text-grey-light`} /> {children}
    </components.SingleValue>
  )

The main issue is with type definitions that expects that children passed to components.SingleValue must be a string.

like image 553
Andro Bermúdez Serrano Avatar asked Oct 26 '25 09:10

Andro Bermúdez Serrano


1 Answers

You don´t have to use the standard components. You can easlily create a custom one but still keep the styles it needs.

The only requirement you need is emotion to get the styles the SingleValue component uses.

/**
 * This Example uses the `FontAwesome` React library.
**/

const options = [
  { label: "Value A", value: "a", icon: faCoffee },
  { label: "Value B", value: "b", icon: faCar },
  { label: "Value C", value: "c", icon: faMobile },
  { label: "Value D", value: "d", icon: faCircle },
  { label: "Value E", value: "e", icon: faSquare }
];

const SingleValue = ({
  cx,
  getStyles,
  selectProps,
  data,
  isDisabled,
  className,
  ...props
}) => {
  console.log(props);
  return (
    <div
      className={cx(
        emotionCss(getStyles("singleValue", props)),
        {
          "single-value": true,
          "single-value--is-disabled": isDisabled
        },
        className
      )}
    >
      <FontAwesomeIcon icon={data.icon} style={{ marginRight: 10 }} />
      <div>{selectProps.getOptionLabel(data)}</div>
    </div>
  );
};

export default class MySelect extends Component {
  render() {
    return (
      <Select
        options={options}
        components={{ SingleValue }}
        styles={{
          singleValue: (provided, state) => ({
            ...provided,
            display: "flex", // To keep icon and label aligned
            alignItems: "center"
          })
        }}
      />
    );
  }
}

Working example


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!