zianwar
zianwar

Reputation: 3740

Draft.js editor is empty

How to test if the content of draftjs editor is empty?

The only idea that I have now is an object comparison against the object returned from this function : EditorState.createEmpty().getCurrentContent()

Upvotes: 16

Views: 12423

Answers (5)

Neeraj Shukla
Neeraj Shukla

Reputation: 41

// All just you need is:
const contentState = editorState.getCurrentContent();
const rawContentState = convertToRaw(contentState);
const text = rawContentState.blocks[0].text.trim();

//See the full code below:
   

const [editorState, setEditorState] = useState(EditorState.createEmpty());
const [errorMessage, setErrorMessage] = useState('');


const handleSubmit = () => {
  const contentState = editorState.getCurrentContent();
  const rawContentState = convertToRaw(contentState);
  const text = rawContentState.blocks[0].text.trim();

  if (text === '') {
    setErrorMessage('Please enter some content before submitting.');
  } else {
    // Proceed with submission logic
    setErrorMessage('');
    // Your submission logic goes here
  }
};

Upvotes: 0

chenjiahe
chenjiahe

Reputation: 29

const text=editorState.getCurrentState().getPlainText()
return text===''

Upvotes: 0

Zanyar Jalal
Zanyar Jalal

Reputation: 1864

 contentState.hasText() && contentState.getPlainText().length > 0 

Check

  • Empty
  • White Space

Upvotes: 6

zianwar
zianwar

Reputation: 3740

Just use the hasText function on ContentState :

editorState.getCurrentContent().hasText()

Upvotes: 61

MinLoveSu
MinLoveSu

Reputation: 243

export const isEmptyDraftJs = (rawState) => {
  if (!rawState || _.isEmpty(rawState)) { // filter undefined and {}
    return true;
  }
  const contentState = convertFromRaw(rawState);
  return !(contentState.hasText() && (contentState.getPlainText() !== ''));
};

I am not sure it is perfect but I use above code.

When you add just image, there is an space character so getPlainText() can filter only image draftJS.

Upvotes: 2

Related Questions