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});
};
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')
);