recile
recile

Reputation: 431

How to do the single element view should look like multi in react-select?

How to do in single element removal as in multi in react-select? The single element view should look like multi. in the sense with the delete button enter image description here

<Select

    isMulti
    name="colors"
    options={colourOptions}
    className="basic-multi-select"
    classNamePrefix="select"
  />

https://codesandbox.io/s/vozjb?module=/example.js

Upvotes: 0

Views: 208

Answers (2)

recile
recile

Reputation: 431

import React, { useState } from "react";

import Select from "react-select";
import { colourOptions } from "./docs/data";

export default () => {
  const [x, setX] = useState({
    value: "ocean",
    label: "Ocean",
    color: "#00B8D9",
    isFixed: true
  });
  return (
    <Select
      value={x ? [x] : []}
      isMulti
      name="colors"
      options={colourOptions}
      className="basic-multi-select"
      classNamePrefix="select"
      onChange={values => setX(values ? values[values.length - 1] : undefined)}
    />
  );
};

https://codesandbox.io/s/react-select-single-as-milti-snwm1

Upvotes: 0

ravibagul91
ravibagul91

Reputation: 20765

In react-select you have styles prop which can be used for styling,

<Select
  isClearable
  defaultValue={options[0]}
  options={options}
  styles={customStyles}
/>

And the styles are,

const customStyles = {
  singleValue: styles => ({ ...styles, 
  color: '#f3f4f5',
  backgroundColor: '#000',
  padding: 5,
  marginRight: 10,
  borderRadius: 4,
  // ...cross()   //This will give you feel of multi select but clicking on this will not work
  }),
  clearIndicator: (base, state) => ({
  ...base,
  cursor: 'pointer',
})
}

For Clearing as multi-select, you can use isClearable prop.

Demo


Update

Another way is, restricting multi-select to select only 1. For this you need to keep a copy of options in state and pass options from state, and using onChange you can restrict,

<Select
  isMulti
  options={this.state.option}
  onChange={values => this.handleSelectChange(values)}
/>

And handleSelectChange function should be,

handleSelectChange = (value) =>{
    if(value!==null){
      if(value.length === 1){
        this.setState({option: value})
      }else{
        this.setState({option: options}) //here options is original options
      }
    }else{
      this.setState({option: options})
    }
}

Upvotes: 1

Related Questions