Keystone.js custom fields: text with autocomplete
Tags: nextjs, typescript, keystonejs, react
Published: 2022-02-06 21:21:27

---
title: Keystone.js custom fields: text with autocomplete
published: true
date: 2022-02-06 20:25:55 UTC
tags: nextjs,typescript,keystonejs,react
canonical_url: https://medium.com/@maciejrokrawczyk/keystone-js-custom-fields-text-with-autocomplete-aef84f8e52fc
---

![keystone](https://cdn-images-1.medium.com/max/1024/1*Nk-Up-zBRJkjyul3kMrAow.jpeg)
_Photo by Bicanski on Pixnio_

### Problem background

Some websites and apps I’m working for my clients are research projects in humanities especially in archeology. And because of that their needs are pretty specific. On the one hand they require simple webpage to present their research results and fulfil administrative obligations, but on the other hand, they also require custom tailored tools to catalog research data. Usually these are qualitative rather than quantitative data.

Typically, my stack to fulfil this needs is pretty extensive. It starts with WordPress as CMS, working in headless mode with Next.js frontend. And this covers website part. Data collection tool was in most cases custom-made app in Node.js and Express or PHP app with Laravel framework. It was completed by Elasticsearch and another large tools. But most of the time I have gut feeling that’s a bit of overcomplicated solution and for sure bloated one. When I was starting current project, I made decision that I have to find better and lighter way to do that, especially because in this case data model was not so complicated. My research started with looking for other CMS, best in Node.js and headless out of the box. I knew about two of this kind of systems, [Strapi](https://strapi.io/) and [Keystone.js](https://keystonejs.com/). First one is a little to rigid for my taste, but second one looks like perfect solution for my needs. Possibility to define schemas in code and easy configuration was really nice. But after that, I had great aha moment. What if I can also use it to define models for data catalog? Is there possibility to kill two birds with one stone? I believe there is. There was one issue thou, but about this later.

### About Keystone.js

On Keystone website we can read that it is superpowered CMS for developers, with built-in GraphQL support and Management UI in place. Also, there’s new, just released version 6. It has really impressive set of features, authentication and authorization, UI, it uses TypeScript and much more useful and necessary features. The only thing we have to worry is our entities structure. But there are a couple of problems. Abstraction layer is really thick in here. In general, it’s not an issue but in some places may become a concern.

Built-in set of fields which can be used in lists and schemas here is more than enough in most basic cases. But unfortunately my case turned out to be not so basic. Maybe it’s caused by specificity of my project, but I needed some extra fields to work with. The issue was not in the field types provided by Keystone, text or JSON fields are versatile enough to serve many purposes. But their visualization in admin panel can be insufficient sometimes.

During development of this project I had to create three custom fields, but only their UI aspects had to change. Underneath they still are text and JSON fields. First of this three is text field with additional autocomplete and I gonna focus on that in this article.

### Requirements

Text field with autocomplete? It sounds like relationship field from Keystone basic set. Yes, but not really. Relationship means in that case that there are at least two entities connected to each other. In this case I just need to get suggestions from table column corresponding to that field. So, what this field has to have? First, it has to have a possibility to get all suggestions from database (or search engine in my case) while typing, then present them to user and let her/him select one or finish writing own version.

### Documentation info about custom field

Mostly because it’s new, just released version of Keystone.js documentation is not so clear in some places. But part about using custom fields is really nice. Even though for me the most useful part of it was the link to source code of built-in fields (for the moment when I am writing this the link is broken, use [this](https://github.com/keystonejs/keystone/tree/main/packages/core/src/fields/types) instead).

In our case interesting is text field ([code](https://github.com/keystonejs/keystone/blob/main/packages/core/src/fields/types/text/views/index.tsx)). We can use this file as a template for what we want to achieve. In documentation, it’s stated that custom field view have to exports four things: field controller and three React components — Field, Cell and CardValue. Each one responsible for different visualizations. But here we are in comfortable position, to fulfill our requirements we have to change only _Field_ visualization, others are fine, so we can reuse built-in ones. Also, there are no changes in controller, so original one can be reused too.

### Steps to resolve

First what I did was to create separate folder _views_ to hold all custom fields visualizations and subfolder _autocomplete_ for our current visualization. Main file there is _view.tsx_ containing our new field. Because we won’t be modifying field controller and Cell and CardValue components, so we can import them and re-export right away.

{% gist https://gist.github.com/eabald/09d2c6e8dc6df46740fe53eac2c67854 %}

I believe it’s not necessary, but in sake of completion and code readability is reasonable to do it. Also, here we can add rest of necessary imports:

{% gist https://gist.github.com/eabald/ad3c81d4384baa0b45736d0bc0c89550 %}

Here we are importing basic React hooks which will be necessary later, some types from Keystone core library, and built-in field components to blend in our custom components into other fields in Admin UI. Now is time to create our Field component end exports it. Also, we have to declare some basic state of the component. We are going to need it later.

{% gist https://gist.github.com/eabald/f6c0a0c3d407d984f4643fbde8257152 %}

According to documentation props in this case have several properties: _field_ which is object containing all methods and properties form field controller, _value_ holding field value, in this case as an object:

{% gist https://gist.github.com/eabald/59a92b4d05e1407cf768dd7b9de40b59 %}

Mostly it depends on kind of operation we are currently performing. It looks different when user creates entity and differently when it’s updated. Also, there are two boolean values _autoFocus_ and _forceValidation_, both rather self-explanatory. Last one there is method _onChange_ which is value setter here. Additionally, I am not pretty sure why, but it is optional, and we have to keep that in mind. Ok, now it’s time to construct our component JSX:

{% gist https://gist.github.com/eabald/24e59b689c03391df44906ddac982ec0 %}

There are to main parts of this component. First one creates text input using built-in components (with some extra events handlers) and simple suggestions list created using _ul_ and _li_ tags. Also, here we can see usage of _visible_ component state. It’s responsible for showing list of suggestions on focus event (and hiding on blur).

Skeleton of the component is in place, now we have to add some muscles to it and add missing methods _onChange_ (our one, not the one coming from props), _onSuggestionClick_ and _setOnChange_ helper.

{% gist https://gist.github.com/eabald/433ed2e16962b19a654f1ca3e595673f %}

First of these methods, _setOnChange_ is a kind of helper function responsible for calling _props.onChange_ method and setting new value of field. As I mentioned before, it’s optional, so we have to close it inside _if_ statement and then call it with new value (keeping in mind, how this value should look like). Next one, _onChange_ fires on each change event. It calls _SetOnChange_ first and then starts to look for suggestions, if the input is more than 3 characters long it calls async method _getSuggestions_ with current input value and then calls set state method _setSuggestions_. Otherwise, if input is too short it sets suggestions to empty array. I believe, in some cases it maybe necessary to debounce this method, but I’ve decided not to. Last one _onSuggestionClick_ sets field value to the value of clicked suggestion.

Next we need to create previously mentioned method _getSuggestions_:

{% gist https://gist.github.com/eabald/881f15179a095f35c74ae7c7c8f93253 %}

Its purpose is simple, it fetches data from server in JSON format and returns suggestions. In this case it is a custom endpoint created according to docs ([more](https://keystonejs.com/docs/apis/config#extend-express-app)):

{% gist https://gist.github.com/eabald/62f4e826d4395282c60820d837688974 %}

It’s simple Express.js route calling _autocomplete_ method and returning results as JSON. It takes three parameters: query to search, index to search in and field to return. In my case under the hood it uses [Meilisearch](https://github.com/meilisearch/Meilisearch) search engine and its JS integration — [Meilisearch JavaScript](https://github.com/meilisearch/meilisearch-js). It’s really nice, reliable and what’s the most important lightweight search engine, useful alternative to huge Elasticsearch. But I am using it because it’s also needed in other part of the system, in other cases using built-in _QueryAPI_ should be enough.

Lastly we have to add a bit of reactiveness to our component, in order to do that we have to add two _useEffect_ hooks and one _useCallback_:

{% gist https://gist.github.com/eabald/eb9a23c481a4865b3cb3501f2a9af123 %}

First, we create memoized callback to load initial suggestions on component loads and value is already set (in case of editing record). I used this hook to make sure that this method is only declared once, on component render. And then we call it inside first _useEffect_ hook, the one running only on component render. Whole idea here is to already have the suggestions when user starts editing the corresponding field. Last hook changes visibility of suggestions based on length of suggestions state array.

Now our component is working as planed, but there’s still one issue. It’s not pretty at all, so we have to add some styling to blend it better with the rest of UI. I moved entire styles to separate file just to not make it messy, but it’s strictly personal.

{% gist https://gist.github.com/eabald/a82880afa64ea55358a866fa5906ab83 %}

Here I’ve decided to use [Emotion](https://emotion.sh/docs/introduction) library just because I know it enough, and it does its job perfectly. Styles here mostly mimic built-in ones to help our custom component to blend into UI and look like it was always there.

So, here’s complete component:

![Component in action](https://cdn-images-1.medium.com/max/715/1*wF0XNkh6KshS8L2ACBByEg.jpeg)
_Component in action_

{% gist https://gist.github.com/eabald/e61f8187388cea20de4f07bc64e261ec %}

### Summary

To sum up: using custom fields in Keystone.js is not that hard (at least custom visualizations for fields). It requires a bit of research and clear idea what we want to achieve, but it can easily resolve minor problems. And most important can save use from writing full-fledged custom system where it’s not needed. When I was starting my first job as a junior web developer, someone told me that real dev knows when to use library/framework and only adopt it and when is better to make custom solution. I believe even though couple of years passed I am still learning this.

To be honest it’s the first article I’ve ever written. I hope it’s clear and informative, and I really appreciate your feedback. I am also planing to write about another two custom fields I’ve needed to create. And I am challenging myself to publish one each week. I hope it will work out. See you in the next one!