Skip to content

Instantly share code, notes, and snippets.

@shalkam
Created May 18, 2017 13:04
Show Gist options
  • Save shalkam/f73ffc4e47c239bdf92f494b0932b158 to your computer and use it in GitHub Desktop.
Save shalkam/f73ffc4e47c239bdf92f494b0932b158 to your computer and use it in GitHub Desktop.
Formsy react-draft-wysiwyg component
import React from 'react';
import Formsy, { HOC } from 'formsy-react';
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, convertToRaw } from 'draft-js';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import { stateToHTML } from 'draft-js-export-html';
import { stateFromHTML } from 'draft-js-import-html';
class Draft extends React.Component {
state = {
editorState: EditorState.createEmpty(),
value: null
};
componentWillReceiveProps(newProps) {
this.setState({ value: this.props.getValue() });
if (newProps.getValue() !== this.state.value) {
const editorState = EditorState.createWithContent(stateFromHTML(newProps.getValue() || ''));
this.setState({ editorState });
}
}
componentWillMount() {
this.setState({ value: this.props.getValue() });
}
// setValue() will set the value of the component, which in
// turn will validate it and the rest of the form
changeValue() {
const HTML = stateToHTML(this.state.editorState.getCurrentContent());
console.log(HTML);
this.props.setValue(HTML);
}
handleEditorStateChange(editorState) {
this.setState({ editorState });
}
render() {
// Set a specific className based on the validation
// state of this component. showRequired() is true
// when the value is empty and the required prop is
// passed to the input. showError() is true when the
// value typed is invalid
const className = this.props.showRequired()
? 'required'
: this.props.showError() ? 'error' : null;
// An error message is returned ONLY if the component is invalid
// or the server has returned an error message
const errorMessage = this.props.getErrorMessage();
return (
<div className={className ? className + ' form-group row' : 'form-group row'}>
<label className="control-label col-sm-3">
{this.props.label}
</label>
<div className="col-sm-9">
<Editor
{...this.props}
editorState={this.state.editorState}
onEditorStateChange={this.handleEditorStateChange.bind(this)}
onBlur={this.changeValue.bind(this)}
/>
<span>{errorMessage}</span>
</div>
</div>
);
}
}
export default HOC(Draft);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment