We're building a custom UI field. It looks like this:
import { merge } from 'lodash';
import { Field } from 'payload/types';
import { LinkTo } from './ui/LinkTo';
interface Options {
collectionSlug: string;
}
// By dynamically building fields in code configurations are reusable and concise
export const linkTo = (options: Options, overrides?: Partial<Field>): Field => {
const { collectionSlug } = options;
return merge<Field, Partial<Field> | undefined>(
{
name: 'linkTo',
type: 'ui',
admin: {
position: 'sidebar',
components: {
Field: (props: Field) => (
<LinkTo {...props} collectionSlug={collectionSlug} />
),
},
},
},
overrides
);
};
// usage
const Tag = {
slug: 'tags',
fields: [
//...
linkTo({ collectionSlug: 'tags' }),
//...
]
}
You can see two twisted place:
linkTo({ collectionSlug: 'tags' })
I already passed a slug in to collection config, but I still need to pass it again.I think if I can get the current collection slug directly in the LinkTo
component would be much easier.
const config = useCollectionConfig();
LinkTo
already gets the field config as the input props, but I cannot pass any additional config to it except writing a wrapper component like this.I think if I can pass some custom configurations would be much easier:
{
name: 'linkTo',
type: 'ui',
admin: {
position: 'sidebar',
collectionSlug,
components: LinkTo,
},
// or an explicit field to pass custom configs
custom: {
collectionSlug,
}
},
// Get collectionSlug from custom config
const LinkTo = ({ admin: { collectionSlug } }) => {
}
I found I can get the current collection info with hook: useDocumentInfo
. It can solve this specific issue for now:
const { collection } = useDocumentInfo();
const collectionSlug = collection?.slug || '';
// or in non react component
const getCurrentCollectionSlug = () => {
const match =
/\/admin\/collections\/([a-z-]*)\/.*/.exec(window.location.pathname) || [];
if (!match) return '';
return match[1];
};
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.