Skip to content

Instantly share code, notes, and snippets.

@BirknerAlex
Last active April 18, 2025 18:07
Show Gist options
  • Save BirknerAlex/dd63a499190ea42c08bd2c682df156f5 to your computer and use it in GitHub Desktop.
Save BirknerAlex/dd63a499190ea42c08bd2c682df156f5 to your computer and use it in GitHub Desktop.
Payload CMS Font Awesome Select Field
import { Field } from 'payload';
export const FontAwesomeField: Field = {
name: 'fontAwesomeIcon',
label: 'Icon',
type: 'text',
validate: (value) => {
if (!value) {
return 'Please select an icon';
}
return true;
},
admin: {
components: {
Field: '@/components/payload/FontAwesome#Select',
},
},
required: true,
hasMany: false,
localized: false,
};
'use client';
import * as React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
IconName,
IconPrefix,
IconProp,
} from '@fortawesome/fontawesome-svg-core';
import { SelectInput, useField, FieldLabel } from '@payloadcms/ui';
import { OptionObject } from 'payload';
import { library } from '@fortawesome/fontawesome-svg-core';
import { fas } from '@fortawesome/free-solid-svg-icons';
import { fab } from '@fortawesome/free-brands-svg-icons';
library.add(fas, fab);
export const fontAwesomeIconOptions = () => {
const options: OptionObject[] = [];
[fas, fab].forEach((iconPack) => {
Object.keys(iconPack).forEach((icon) => {
options.push({
label: icon,
value: iconPack[icon].prefix + '/' + iconPack[icon].iconName,
});
});
});
return options;
};
type FontAwesomeSelectComponentProps = {
path: string;
};
export const Select: React.FC<FontAwesomeSelectComponentProps> = ({ path }) => {
const { value, setValue } = useField<string>({ path });
let icon: IconProp = { prefix: 'fas', iconName: 'question' };
if (value) {
icon = value.split('/') as [IconPrefix, IconName];
}
return (
<div>
<SelectInput
path={path}
name={path}
value={value}
required={true}
label={'Icon'}
description={
'You can find all icons on the page https://fontawesome.com/icons'
}
hasMany={false}
options={fontAwesomeIconOptions()}
onChange={(e) => {
setValue(e?.value);
}}
/>
{value && icon && (
<span>
Icon Preview: <FontAwesomeIcon icon={icon} />
</span>
)}
</div>
);
};
@kylemcshea
Copy link

In tandem to this code you must also install your dependencies:

npm install @fortawesome/react-fontawesome @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/free-brands-svg-icons

@dreamy38
Copy link

image

Is this for payload v3?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment