I am trying to use draft-js for Rich Text Editor in my app, with redux-form, the problem I am facing is I am not able to populate initialValues into the Editor from draft-js, my code looks like this
<form onSubmit={handleSubmit(this.onFormSubmit.bind(this))}>
<Field
name="websiteurl"
placeholder="INSERT WEBSITE URL HERE"
component={this.renderFieldText}
mandatory='true'
/>
<Field
name="htmlcontent"
placeholder="ENTER HTML CONTENT HERE"
component={this.renderRichTextEditor}
/>
<Button bsStyle="primary" type="submit" className="pull-right" loading={this.state.loading}>Save</Button>
</form>
renderRichTextEditor(field){
return (
<RichTextEditor placeholder={field.placeholder}/>
);
}
renderFieldText(field){
var divClassName=`form-group ${(field.meta.touched && field.meta.error)?'has-danger':''}`;
divClassName = `${divClassName} ${field.bsClass}`;
return(
<div className={divClassName}>
<input
className="form-control"
type={field.type}
placeholder={field.placeholder}
{...field.input}
/>
</div>
);
}
I have two fields websiteurl
and htmlcontent
, the component websiteurl
gets populated with initialValues, but I am not getting how to do this with draft-js Editor which is implemented inside RichTextEditor component..
If anyone has achieved something like this, please help.
Thanks.
I like to create a separate component for the Rich Editor's "field component" in order to not muddy up the form component. Personal preference really.
<Field name="content" component={EditorField} />
Moving to the EditorField component...
constructor(props: Props) {
super(props);
// here we create the empty state
let editorState = EditorState.createEmpty();
// if the redux-form field has a value
if (props.input.value) {
// convert the editorState to whatever you'd like
editorState = EditorState.createWithContent(convertFromHTML(props.input.value));
}
// Set the editorState on the state
this.state = {
editorState,
};
}
Write the onChange function
onChange = (editorState: Object) => {
const { input } = this.props;
// converting to the raw JSON on change
input.onChange(convertToRaw(editorState.getCurrentContent()));
// Set it on the state
this.setState({ editorState });
};
Now in the render function, go ahead and place your editor component. Pass the Redux Form input props, your onChange function and the editor state.
<Editor
{...input}
onEditorStateChange={this.onChange}
editorState={editorState} />
Now you can set the initialValues like you normally would using redux-form without Draft-js.