reactjsdraftjsreact-draft-wysiwyg

Unable to get entered data in a rich text editor (react-draft-wysiwyg) included to React component


I am working on creating a React component with a rich text editor included. I chose react-draft-wysiwyg for editing or creating texts and then sending to the server. I will give in the code only the functionality that causes difficulties. I use axios to send requests. For some reason, I can’t get the correct data from the form when sending a POST request. I checked using commands:

console.log(data);
console.log(this.state.editorState);

But there is now text typed in the form. I would like to figure it out, thanks to everyone!

Here is the code:

import React, { Component } from 'react';
import { EditorState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import '../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import axios from 'axios';

class AddPost extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty()
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange = (e) => {
    this.setState({[e.target.name]: e.target.value})
  }

  onEditorStateChange = (editorState) => {
    this.setState({
      editorState
    });
  }

  handleSubmit(e) {
    e.preventDefault();

    const data = {
      content: this.state.editorState
    };

    axios.post('http://localhost:5555/posts', {data})
      .then(res => {
        console.log(data);
      })

    this.setState({editorState: EditorState.createEmpty()})
  }
  render() {
    return (
      <div>
        <h5>Create document</h5>        
          <Editor
            editorState={this.state.editorState}
            wrapperClassName="demo-wrapper"
            editorClassName="demo-editor"
            onEditorStateChange={this.onEditorStateChange}
          />
          <button onClick={this.handleSubmit} className="btn-large waves-effect waves-light xbutton">Save</button>        
      </div>
    );
  }
}

export default AddPost;

Solution

  • To get data from draft-js editor you need to use

    this.state.editorState.getCurrentContent().getPlainText();