Custom field settings

System Information
  • Strapi Version: 4.4.5
  • Operating System: Ubuntu 20.04
  • Database: MySQL 8.0.30
  • Node Version: 14.20.0
  • NPM Version: 6.14.17
  • Yarn Version: 1.22.19

Hello to everybody.
Via plugin I’m playing with custom fields, but can’t figure out how to pass configuration data to react components.

// /config/plugins.ts

export default {
  // ...
 'my-strapi-awesome-plugin': {
    enabled: true,
    resolve: './src/plugins/my-strapi-awesome-plugin',
    config: {
      apiKey: 'qwertyui1234',
      color: '#44008D'
    },
  },
// ...
}

But Inside my component I don’t have any access to strapi global object to make the following call

strapi.plugin('my-strapi-awesome-plugin').config('color')

How can i do?


Hi Arrigo,

it seems to me that the config is only present in the server for security reasons. You want to protect your api key from public access. So I would write an endpoint, and make some configurations public. In the component you can then get your configuration via the endpoint.

src/plugins/yourPluginName/server/controllers/my-controller.ts

export default ({ strapi }: { strapi: Strapi }) => ({
  async getColorFormConfig() {
    return strapi.plugin(pluginName).config("color", "#000");
  },

Then you need to register the controller here: src/plugins/yourPluginName/server/controllers/index.ts

import myController from './my-controller';

export default {
  myController,
};

You will also need a route.

export default [
  {
    method: "GET",
    path: "/",
    handler: "myController.getColorFormConfig",
    config: {
      policies: [],
      auth: false,
    },
  }
];

Now you can fetch the color setting from your component.
http://localhost:1337/yourPluginName

Greets

Another way is to put your configuration to the options.

// src/plugins/yourPluginName/admin/src/index.tsx

export default {
  register(app: any) {
    app.customFields.register({
      name: fieldName,
      // ....
      options: {
          advanced: [
          {
            name: "options.color",
            type: "string",
            defaultValue: "#000",
            intlLabel: {
              id: `${pluginName}.${fieldName}.options.advanced.color`,
              defaultMessage: "Color",
            },
            description: {
              id: `${pluginName}.${fieldName}.options.advanced.color.description`,
              defaultMessage: "You can set the color here",
            },
          },
      }
 // ....

And then in your Component you can access on this option like this

export function YourCustomField(props: Props) {
  const { attribute } = props;
  return <div>{attribute.options.color}</div>
}