Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
kb1995 opened this issue Jan 13, 2023 · 5 comments
Open

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

kb1995 opened this issue Jan 13, 2023 · 5 comments

Comments

@kb1995
Copy link

kb1995 commented Jan 13, 2023

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
Copy link
Author

kb1995 commented Jan 13, 2023

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
Copy link

My attempt in Typescript:

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

@mikedaviesweb
Copy link

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
Copy link

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
Copy link

Jdruwe commented Feb 29, 2024

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;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants