How to Create a Custom Select Field in Payload: A Step-by-Step Guide

Published On
Create a Custom Select field in Payload
Create a Custom Select field in Payload
This quick tutorial will guide you through the process of creating a custom select component, demonstrating how to override default UI components, how to import options from an external API, and storing your custom values.

Let's jump right in and start building a custom select field that you can use in Payload.

The standard select field allows you to choose from multiple options, and these options are predefined and passed directly to the select field.

What we're going to build is a select field that looks and works the same but has its options imported from an external source.

This can help you integrate data from a third party. For example, it might be a list of form IDs or product IDs. It's also really useful when you need to display large, universal data such as countries or national holidays.

First, we want to define our base field.

1
import { Field } from 'payload/types';
2
import { CustomSelectComponent } from './component';
3
4
export const CustomSelectField: Field = {
5
name: 'customSelectField',
6
type: 'text',
7
admin: {
8
components: {
9
Field: CustomSelectComponent,
10
},
11
}
12
}

Although we're building a select component, it's important to note that we won't be using the select type. The select type field's underlying structure is an enum and must be predefined. Since this custom field will use external options, that approach won't work.

Instead, we're going to use the type text. Then we want to override the front-end field. To do this, we'll pass in our own component to the admin components field.

Now, let's get into the custom component.

1
import * as React from 'react';
2
import { SelectInput, useField } from 'payload/components/forms';
3
4
export const CustomSelectComponent: React.FC<{ path: string }> = ({ path }) => {
5
const { value, setValue } = useField<string>({ path });
6
const [options, setOptions] = React.useState([]);
7
8
// Fetch options on component mount
9
React.useEffect(() => {
10
const fetchOptions = async () => {
11
try {
12
const response = await fetch('https://restcountries.com/v3.1/all');
13
const data = await response.json();
14
15
const countryOptions = data.map((country) => {
16
return {
17
label: `${country.name.common + ' ' + country.flag}`,
18
value: country.name.common,
19
};
20
});
21
22
setOptions(countryOptions.sort(
23
(a, b) => a.label.localeCompare(b.label)
24
));
25
} catch (error) {
26
console.error('Error fetching data:', error);
27
}
28
};
29
30
fetchOptions();
31
}, []);
32
33
return (
34
<div>
35
<label className='field-label'>
36
Custom Select - Countries
37
</label>
38
<SelectInput
39
path={path}
40
name={path}
41
options={options}
42
value={value}
43
onChange={(e) => setValue(e.value)}
44
/>
45
</div>
46
)
47
};

Essentially, what we're doing here is replicating the existing Payload select field and then passing in our own options – simple as that!

The first thing we're going to do is import the existing select component directly from Payload. After that, we'll want to output this component ourselves.

The select component will require the path, name, your options, and value.

We can also import the useField function from Payload, which will help us get and set the value.

The field path can be de-structured directly off the component and then passed in to our useField function. From that function, we can de-structure value and also a setValue function.

So, if you go and take another look, you can see where the path is coming from, along with the value and setValue.

1
return (
2
<div>
3
<label className='field-label'>
4
Custom Select - Countries
5
</label>
6
<SelectInput
7
path={path}
8
name={path}
9
options={options}
10
value={value}
11
onChange={(e) => setValue(e.value)}
12
/>
13
</div>
14
)

Now onto our options.

The first thing we want to do is define an empty state. Then, we come down to our fetchOptions async function.

Essentially, what this function needs to do is pull in your data and then restructure the shape of data so that you can output it as an array of objects, each with a label and a value.

To start, it's making a fetch request to the restcountries.com API, and then we wait for that response to be converted into JSON.

Next, we're going to map over that JSON data and return a label and value for each country.

1
React.useEffect(() => {
2
const fetchOptions = async () => {
3
try {
4
const response = await fetch('https://restcountries.com/v3.1/all');
5
const data = await response.json();
6
7
const countryOptions = data.map((country) => {
8
return {
9
label: `${country.name.common + ' ' + country.flag}`,
10
value: country.name.common,
11
};
12
});
13
14
setOptions(countryOptions.sort(
15
(a, b) => a.label.localeCompare(b.label)
16
));
17
} catch (error) {
18
console.error('Error fetching data:', error);
19
}
20
};
21
22
fetchOptions();
23
}, []);

Now, we're back to the useState setOptions function.

Within the function, I've added a couple lines of code to put the countries in alphabetical order. But essentially, we're just setting those options back into our options state.

It's also important that we wrap all of this in a try catch so that if anything goes wrong, we won't break the whole admin panel.

Finally, we only want to run this function once. So, we're running this function inside of a useEffect with no dependencies, which means this will only run once when the component initially mounts.

One last tip: you can add the class name field-label, and Payload will automatically apply styles to this so that it matches everything else.

And that is it!

A custom select field with a dropdown list of countries, in the typical Payload style

Earlier, we talked about a regular select, and now appearing just the same is our nice, new custom select with all the countries - and if take a look at the data, you will see the new `customField` and its value.

1
{
2
"id": "64dele85d24a52f3cbc179e2",
3
"customSelectField": "Poland",
4
"createdAt": "2003-08-17T13:20:05.661Z",
5
"updatedAt": "2023-08-17T03:22:20.766Z"
6
}

Here is a link to the GitHub repo containing this code .

If you have any questions, be sure to join us on Discord!