Nilanjana
Nilanjana

Reputation: 131

how to set a maxlength property for react-rte editor

How to impose a restriction for the number of character inside a react-rte editor? is there any property like "maxlength" ?

Upvotes: 1

Views: 3272

Answers (2)

Blaise Izabayo
Blaise Izabayo

Reputation: 1

import React, { Component } from 'react';
import RichTextEditor from 'react-rte';

const toolbarConfig = {
  display: ['INLINE_STYLE_BUTTONS', 'HISTORY_BUTTONS', 'BLOCK_TYPE_BUTTONS'],
  INLINE_STYLE_BUTTONS: [
    { label: 'Bold', style: 'BOLD', className: 'custom-css-class' },
    { label: 'Italic', style: 'ITALIC' },
    { label: 'Underline', style: 'UNDERLINE' },
    { label: 'Strikethrough', style: 'STRIKETHROUGH' },
    { label: 'Monospace', style: 'CODE' },
  ],
  HISTORY_BUTTONS: [
    { label: 'Undo', style: 'undo' },
    { label: 'Redo', style: 'redo' },
  ],
  BLOCK_TYPE_BUTTONS: [
    { label: 'Blockquote', style: 'blockquote' },
  ],
};

class MyStatefulEditor extends Component {
  constructor(props) {
    super(props);
    this.initialValue = RichTextEditor.createValueFromString(props.markup, 'html');
    this.state = {
      value: this.initialValue,
    };
  }

  handleChange = (value) => {
    const { onChange } = this.props;
    this.setState({ value });

    // Extract plain text from value
    const plainText = value.getEditorState().getCurrentContent().getPlainText('');
    const textLength = plainText.length;

    if (onChange) {
      onChange(value.toString('html'), textLength);
    }
  };

  render() {
    const { value } = this.state; // Include textLength in the state

    return (
      <RichTextEditor
        value={value}
        onChange={this.handleChange}
        toolbarConfig={toolbarConfig}
      />
    );
  }
}

export default MyStatefulEditor;

using value.getEditorState().getCurrentContent().getPlainText('') would help you to know the length of the actual text

Upvotes: 0

Aftab Khan
Aftab Khan

Reputation: 3923

react-rte internally uses draftjs.

This answer should work for you: How to limit Max Length of Draft js

Upvotes: 1

Related Questions