Skip to content

Instantly share code, notes, and snippets.

@akkikumar72
Created August 30, 2021 12:58
Show Gist options
  • Save akkikumar72/ea1839d1535cff85f30441f15279e7a5 to your computer and use it in GitHub Desktop.
Save akkikumar72/ea1839d1535cff85f30441f15279e7a5 to your computer and use it in GitHub Desktop.
Multi-Select &
import React from 'react';
import Select, { components as Components } from 'react-select';
import './multi-select.scss';
import Checkbox from '../checkbox';
const customStyles = {
container: (provided) => ({
...provided,
width: '60%'
}),
valueContainer: (base) => ({
...base,
height: '40px',
'min-height': '40px'
})
};
const Option = (props) => (
<Components.Option {...props}>
<Checkbox title={props.label} id={props.label} checked={props.isSelected} onChangeEvent={() => null} />
</Components.Option>
);
const MultiValue = (props) => (
<Components.MultiValue {...props}>
<span>{props.data.label}</span>
</Components.MultiValue>
);
const MultiSelect = (props) => {
const { isMulti, value, onChange } = props;
const handleRemoveValue = (e) => {
if (!onChange) return;
const { name: buttonName } = e.currentTarget;
const removeValue = value.find((val) => val.label === buttonName);
if (!removeValue) return;
onChange(
value.filter((val) => val.label !== buttonName),
{ name, action: 'remove-value', removeValue }
);
};
return (
<>
<Select
{...props}
styles={customStyles}
closeMenuOnSelect={false}
components={{ Option, MultiValue, IndicatorSeparator: () => null }}
hideSelectedOptions={false}
isDisabled={false}
isClearable={false}
placeholder='Add to group'
backSpaceRemovesValue={false}
controlShouldRenderValue={!isMulti}
/>
<div className='multiSelect'>
{isMulti
? value.map((val) => (
<div className='multiSelect-value' key={val.value}>
{val.label}
<button className='multiSelect-value-crossBtn' name={val.label} onClick={handleRemoveValue}>
x
</button>
</div>
))
: null}
</div>
</>
);
};
export default MultiSelect;
.multiSelect{
display: flex;
flex-wrap: wrap;
align-items: center;
margin-top: 0.5rem;
&-value{
padding: 0.3rem 0.5rem 0.3rem 0.5rem;
margin: 0 0.55rem;
font-size: 1rem;
border: 1px solid #b3b3b3;
color: #686868;
background-color: #fafafa;
user-select: none;
&-crossBtn{
all: unset;
margin-left: 0.3rem;
color: black;
transition: fill 0.15s ease-in-out;
cursor: pointer;
&:hover {
color: #bb392d;
}
&:focus {
color: #c82f21;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment