claus / storyblok-rich-text-react-renderer

A React renderer for Storyblok rich text content
MIT License
86 stars 16 forks source link

Is there an easy way to check if a rich text field is empty? #27

Open kb1995 opened 1 year ago

kb1995 commented 1 year ago

I'm not sure if this is in the scope of this library, but it might be quite useful if we provide a function to check if the rich text field is empty or not.

This is what an empty rich text field looks like at the moment

{
    "type": "doc",
    "content": [
        {
            "type": "paragraph"
        }
    ]
}

Coming from other headless CMS, I know that there might be a couple of different edge cases which we might need to cover.

kb1995 commented 1 year ago

I quickly created a function to check if the rich text field is not empty. Let me know if I'm missing something obvious

export const richTextIsNotEmpty = (field) => {
  if (!field) {
    return false;
  }

  if (field.content?.length === 1) {
    const content = field.content[0];
    if (!("content" in content)) {
      return false;
    }
  }

  return true;
};
Gerosullivan commented 1 year ago

My attempt in Typescript:

export const fieldHasValidContent = (field: { content: any[] }) =>
  Array.isArray(field?.content) && 'content' in field.content[0]
mikedaviesweb commented 1 year ago

The render() function returns null if the rich text field is empty, so you can simply do this:

{render(myRichTextField) && (
  <div>
     {render(myRichTextField)}
  </div>
)}
javierdebug commented 1 year ago

On the same topic, is there a way to check if there is an empty line? For example, if an editor presses Enter and leaves the first line without content or forgets to remove the last line

Jdruwe commented 6 months ago

I wrote this utility function, hopefully it could be of help to someone:

const isRichTextConfigured = (document: SBrichtext) => {
    if (document.content) {
        for (const item of document.content) {
            if (Array.isArray(item.content) && item.content.length > 0) {
                return true;
            }
        }
    }
    return false;
};