Currenlt im trying to customizing the multiple Select component in Ant Design to meet specific requirements. However, im uncertain about the possibility of fully customizing this component according to my needs.
What i expect
What i got
The scenario is something like this:
Suppose we have a Multiple Select element containing 10 options. In cases where the count of selected options is less than 4, we will display the regular tags in their default style. However, if the count surpasses 4, i want to eliminate all individual tags, and instead, show 1 tags that count total of selected options as shown in the picture
Currently, i use tagRender
prop to customize the rendering of tags. Nevertheless, this customization is executed for each item within the selected list. To address this, the objective is to confine this customization function to execute only once, generating a single tag. Any strategies or alternatives that achieve this outcome would be greatly appreciated.
here’s my code
const renderTags = (props) => {
const { label } = props
const tagCount = selectedValues.length
if (tagCount < 4) {
return <span className="custom-tag-item">{label}</span>
}
return <span>Numbers of Campaigns: {tagCount}</span>
}
<Select
className="custom-multiple-select"
popupClassName="custom-popup"
mode="multiple"
placeholder={placeholder}
size={size}
defaultValue={['a10', 'c12']}
onChange={handleChange}
options={options}
suffixIcon={
<img
className={`down-arrow ${isDropDownOpen ? 'rotate' : 'rotate-backward'}`}
src={DownArrow}
alt="down arrow icon"
/>
}
onDropdownVisibleChange={() => setDropDownOpen(!isDropDownOpen)}
tagRender={renderTags}
/>
You need to use maxTagCount and maxTagPlaceholder props. To render first 3 options, use tagRender
prop and just return your custom tag. When selected options length is greater than 3 than set maxTagCount
to 0 and use maxTagPlaceholder
to render custom max tag.
import { useState } from 'react';
import { Select } from 'antd';
const options = Array.from({ length: 10 }, (_, i) => ({ value: i + 1, label: `Option ${i + 1}` }));
const App = () => {
const [value, setValue] = useState([]);
const maxTagCount = value.length > 3 ? 0 : undefined;
return (
<Select
value={value}
onChange={setValue}
options={options}
mode="multiple"
maxTagCount={maxTagCount}
tagRender={(props) => {
const { label } = props;
return <span className="custom-tag-item">{label}</span>;
}}
maxTagPlaceholder={() => <span>Numbers of Campaigns: {value.length}</span>}
/>
);
};
export default App;
For more info, please follow Antd Select API