Reputation: 43
Is it possible to render customized option in antd select?
here's what I came up with. I want checkbox to be rendered alongside option.
However, I get default options.
Here are my 'CustomSelect' and 'CustomOption' components.
// CustomSelect.tsx
import React from "react";
import { Select as AntSelect } from "antd";
import { CustomSelectStyle, Wrapper } from "./styles";
import { ReactComponent as ChevronDown } from "@assets/images/chevron-down.svg";
import { NewSelectProps } from "./types";
import { SelectValue } from "antd/lib/select";
import CustomOption from "./CustomOption";
function CustomSelect<T extends SelectValue>({
width = "normal",
mode,
error = false,
children,
...props
}: NewSelectProps<T>) {
return (
<Wrapper width={width}>
<CustomSelectStyle onError={error} />
<AntSelect optionLabelProp="label" mode={mode} {...props}>
{children}
</AntSelect>
<ChevronDown className="dropdown-icon" />
</Wrapper>
);
}
CustomSelect.Option = CustomOption;
export default CustomSelect;
// CustomOption.tsx
import { Select as AntdSelect, Checkbox } from "antd";
import { OptionProps } from "antd/lib/select";
const { Option } = AntdSelect;
interface CustomOptionProps extends OptionProps {
type: "checkbox" | "default";
}
function CustomOption({ type, children, ...props }: CustomOptionProps) {
return (
<Option {...props}>
{type === "checkbox" && <Checkbox />}
{children}
</Option>
);
}
export default CustomOption;
I know that I could just do this...
<CustomSelect
onChange={value => console.log(value)}
error={false}
mode="multiple"
>
<CustomSelect.Option value={"korea"}>
<TextWithCheckbox checked={false}>
korea
</TextWithCheckbox>
</CustomSelect.Option>
<CustomSelect.Option value={"china"}>
<TextWithCheckbox checked={false}>
china
</TextWithCheckbox>
</CustomSelect.Option>
</CustomSelect>
But what I want is to make a new Option Component.
Upvotes: 3
Views: 9220
Reputation: 6885
You don't need a custom CustomOption
component. You can handle custom option renderer in TextWithCheckbox
component like:
const TextWithCheckbox = (props) => {
return (
<div>
<Checkbox checked={props.checked} />
{props.children}
</div>
);
};
You can take a look at this sandbox for a live working example of this code.
Upvotes: 1