I have a react application and using DraftJs.
On listing pages my ContentCard component renders DraftJs content as read-only using Editor from draft-js.
<Editor readOnly={true} editorState={contentState} />
I want to show short version of contentState as short description, max 400 characters at listing pages. And on content detail pages full contentState.
I used this truncate method but it trims only text. Here i get block and then texts. But how can i get blocks with character limit.
For example; First block contains 820 characters with all different styling words. How can i get first 400 characters with all styling information. I mean block with 400 character.
truncate = (editorState, charCount) => {
const contentState = editorState.getCurrentContent();
const blocks = contentState.getBlocksAsArray();
let index = 0;
let currentLength = 0;
let isTruncated = false;
const truncatedBlocks = [];
while (!isTruncated && blocks[index]) {
const block = blocks[index];
const length = block.getLength();
if (currentLength + length > charCount) {
isTruncated = true;
const truncatedText = block
.getText()
.slice(0, charCount - currentLength);
const state = ContentState.createFromText(`${truncatedText}...`);
truncatedBlocks.push(state.getFirstBlock());
} else {
truncatedBlocks.push(block);
}
currentLength += length + 1;
index++;
}
if (isTruncated) {
const state = ContentState.createFromBlockArray(truncatedBlocks);
return EditorState.createWithContent(state);
}
return editorState;
};
I want to show 400 characters with bold, italic styling, links and opher entities and so on.