Search code examples
javascriptreactjsdraftjs

draft js data flow examples


I'm working on a react project where we are going to use a lot of forms, including fields with rich HTML. I searched for a while and stumbled upon draft-js. It seems very good, but I can't seem to find any good examples of how to use it from beginning to end. Most of what I find is how to modify the controls, but that is not what I am looking for. Its basic functionality is all I need at the moment.

I've got it up and working in my form, I have the controls I want, etc., but I just don't know where to go from there.

My structure looks like this:

<Root>
    <FormContainer>
        <FormBody>
            <DraftEditor1>
            <DraftEditor2>
        <FormFooter>
            <CancelButton>
            <SubmitButton>

I have looked into EditorState, convertToRaw, etc., but can't figure out how to access the EditorState from my submit event.

I'm a little new to react as well, but I am thinking that I should put a submit event on the SubmitButton in an onClick handler which is passed down from the FormContainer.

My clickHandler should then fire a Redux Action to save the data in the form.

But in that case, how do I access and convert the EditorState to the correct data format, especially considering that I have multiple DraftEditors in my form?

If you know of any great examples or tutorials out there, please let me know.


Solution

  • I drafted a simple code that can give you an idea:

    ...
    
    _handleSubmit() {
      // dispatch an action
      // or save to redux store
      const { draftEditor1, draftEditor2 } = this.state;
      this.props.handleSubmit(draftEditor1, draftEditor2);
    }
    
    render() {
        return (
          <FormContainer>
            <FormBody>
              <DraftEditor1 editorState={this.state.draftEditor1} onChange={this.onChange1}>
              <DraftEditor2 editorState={this.state.draftEditor2} onChange={this.onChange2}>
            </FormBody>
            <FormFooter>
              <CancelButton />
              <SubmitButton onClick={this._handleSubmit} />
            </FormFooter>
          </FormContainer>
        );
    }
    ...