Ant Design select dropdown with images preview

September 2, 2024

  • Frontend

  • UI

We all know dropdown selectors with options presented as a raw text. But what if we want to have more complex stuff there? Maybe images? Let's try what are the possibilities of Ant Design's Select component.

Select options

In general it's all about writing our own label renderer function for the dropdown option, because the library allows us to pass it as a prop to the Select component.

<Select labelRender={myLabelRender} options={myOptions} />

Please note that myOptions are not only value-label pairs, they need also an image source:

const myOptions = useMemo(() => [
    {
        value: 1,
        label: 'Label 1',
        imageSrc: 'some/nice/image-1.webp',
    },
    {
        value: 2,
        label: 'Label 2',
        imageSrc: 'some/nice/image-2.webp',
    },
], []);

Renderer function definition

const myLabelRender = useCallback((props: LabelInValueType) => {
    const item = myOptions.find((option) => option.value === props.value);

    if (item) {
        return (
            <div
                style={{
                    display: 'flex',
                    flexFlow: 'row nowrap',
                    alignItems: 'center',
                }}
            />
            <div style={{ marginRight: '10px' }}>
                <CloudflareImage
                    width={100}
                    height={50}
                    style={{ objectFit: 'contain' }}
                    src={item.imageSrc}
                    alt={item.label}
                />
            </div>
            <div>
                {item.label}
            </div>
            </div>
        );
    }
}, [myOptions]);

This function is going to render a custom select dropdown option as a row which contains an image and a text - but you can put anything there, e.g. action buttons.

See also 🔗 Cloudflare image optimization in Next.js

Adam Kaczmar

About the author

Adam Kaczmar, Web Developer

I've been a professional full-stack web developer since 2015. My experience comes mainly from e-commerce and consists of:

  • developing highly customized e-commerce software,
  • automating catalog and order integrations with external warehouse services,
  • creating tailor-made user-friendly administration tools for client teams,
  • creating front-end React / Next.js applications along with headless Magento, Laravel and Sanity back-ends.

Besides my programming job, I'm a husband, a father of two lovely daughters and I train boxing every Monday afternoon. Movie genere of my choice is western.

Want to talk? 🙂 Reach me on LinkedIn

...or explore all blog posts ➡️