Search code examples
reactjsgraphqlgatsbynetlifynetlify-cms

How to create custom netlifyCMS widget that can handle a query?


So I want to have a select widget where the options are based on some dynamic data that I have to query for. However, it seems that custom widgets break when importing useStaticQuery.

The below gives me "no control widget in the CMS". It works fine without the useStaticQuery import.

import React from 'react';

import { useStaticQuery, graphql } from "gatsby"

export class CustomControl extends React.Component {

  render() {
      return (
        <div>
          ...
        </div>
      )
  };
}


export const CustomPreview = (props) => {
  return (
    <div></div>
  );
}

Generally, is there a best way/practice to go about creating a custom widget that can handle dynamic values?

Update:

I have tried the relation widget with no luck. I have existing data in a collection but can't seem to access it from the widget. Does someone have a working version of one I can go off of?

The collection that is meant to be the "data":

  - label: Team
    name: team
    folder: 'src/pages/team' 
    create: true
    fields:
      - {label: 'Name', name: 'name', widget: string}

and the relation widget:

 - label: 'Relation widget'
   name: 'relationWidget'
   widget: 'relation'
   collection: 'team'
   searchFields: ['name']
   valueField: 'name'
   displayFields: ['name']

Solution

  • With the NetlifyCMS structure, the best way to access other data is through the relation widget rather than a query.

    However, in order to actually see this working, the site needs to be live. You can't locally mock data. Meaning, you can't go to localhost:8000/admin and see the relation widget pull anything.

    (This is kind of a hassle because you have to authenticate a user as well and rebuild the whole site just to see the one change. It seems like you should be able to either query or just run the CMS locally and mess around with it that way)

    Update

    In order to pass multiple values through a relation widget: value_field: "{{value1}}-{{value2}}"

    create a proxy server to run the CMS locally. This is still in beta at the moment for netlifyCMS but seems to work well. https://www.netlifycms.org/docs/beta-features/