Last active
April 18, 2025 18:07
-
-
Save BirknerAlex/dd63a499190ea42c08bd2c682df156f5 to your computer and use it in GitHub Desktop.
Payload CMS Font Awesome Select Field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In tandem to this code you must also install your dependencies: