0

I have a Draftjs editor in a form with other fields. The state for all those fields is being controlled in that parent component. How do I get the same behavior from the Draft editor as I do from the regular HTML form fields where it updates the parent state?

Regular input:

<input value={title} type="text" onChange={this.handleChange} name="title" placeholder="Title" id="title" />

Draft js editor:

<TextEditor placeholder="Write your summary..." value={summary} toolbar />

On change handler:

handleChange(event) {
  this.setState({[`${event.target.name}`]: event.target.value});
};
humdinger
  • 521
  • 1
  • 3
  • 18

1 Answers1

1

You can simply Do : In parent : (not that I have add the update={ this.update } props)

…
render(){
    return (
    <input value={title} type="text" onChange={this.handleChange} name="title" placeholder="Title" id="title" update={ this.update }/>
    );
}

update(editorState){
  console.log('update',editorState);
}
…

In editor :

handleChange(event) {
  this.setState({[`${event.target.name}`]: event.target.value});
  this.props.update(this.state);
};

This will call the update() function of the parent, is that what you are searching for ?

Edit :

import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';

class Parent extends React.Component {
…
    render() {
      return (
        <div>
            <form>
            <MyEditor update={ this.update }>
            <form>
        </div>
      );
    }
   update(editorState) {
      console.log('editor s state', editorState);
   }
…
}
// from draft website :
class MyEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => {
        this.setState({editorState});
        this.props.update(this.state);
    }
  }
  render() {
    return (
        <Editor editorState={this.state.editorState} onChange={this.onChange} />
    );
  }
}

ReactDOM.render(
  <Parent/>,
  document.getElementById('container')
);
D. Peter
  • 487
  • 3
  • 12
  • I think this would be if I had the other inputs in the editor. I've got the editor in a form along with other inputs instead of other inputs inside the editor. I think I do see your point though that I can pass in a function that takes the editor state and will pass it up. That makes sense. Thank you! – humdinger May 28 '17 at 20:34
  • Yes, passing a function to the child is the only "good" solution I see to update parent's state – D. Peter May 28 '17 at 20:35