Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty elements removed when using convertFromHTML()

Tags:

draftjs

I'm trying to populate a Draft.js 0.10.0 editor with some HTML content when it initializes. The problem is that any HTML block elements that don't have text in them don't get converted to ContentBlocks. So all of the extra spacing from line breaks is removed.

I'd expect the code below (or in jsfiddle) to have some empty ContentBlocks but there are none. Only the elements with text in them get a ContentBlock. It acts the same in Draft 0.9.1 as seen in this jsfiddle so I must be doing something wrong. The HTML can vary but I do have access to it if it needs to be manipulated.

Anyone know how to get empty lines / content blocks to appear with convertFromHTML?

const theHTML =
  '<div>first line</div>' +
  '<div></div>' +
  '<p></p>' +
  '<br />' +
  '<div>&nbsp;</div>' +
  '<p>sixth line</p>' +
  '<div>seventh line</div>';

const {
  Editor,
  EditorState,
  ContentState,
  convertFromHTML
} = Draft;

class Container extends React.Component {
  constructor(props) {
    super(props);
    const blocksFromHTML = convertFromHTML(theHTML);
    const contentState = ContentState.createFromBlockArray(
      blocksFromHTML.contentBlocks,
      blocksFromHTML.entityMap
    );
    this.state = {
      editorState: EditorState.createWithContent(contentState)
    };
  }
  render() {
    return (
      <div className = "container-root" >
      <Editor
        editorState = { this.state.editorState }
        onChange = { this._handleChange } />
      </div>
    );
  }
  _handleChange = (editorState) => {
    this.setState({
      editorState
    });
  }
}

ReactDOM.render( <Container /> , document.getElementById('react-root'))
body {
  font-family: Helvetica, sans-serif;
}

.container-root {
  border: 1px solid black;
  padding: 5px;
  margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/draft-js/0.10.0/Draft.js"></script>

<div id="react-root"></div>
like image 276
Paul Avatar asked Sep 19 '25 17:09

Paul


1 Answers

For me draft-js-import-html solved the problem. The stateFromHTML function converts the html to contentState and keeps empty tags.

Instad of this:

const blocksFromHTML = convertFromHTML(theHTML);
const contentState = ContentState.createFromBlockArray(
  blocksFromHTML.contentBlocks,
  blocksFromHTML.entityMap
);

Simply use this:

 const contentState = stateFromHTML(theHTML);
like image 86
szilagyi.sandor Avatar answered Sep 23 '25 10:09

szilagyi.sandor