Example draft.js
December 4, 2018 ยท View on GitHub
I fyou are new to draft.js there's a great interactive learning resource learn-draftjs.now.sh and also see first basic example usage getting started in docs
Here's an example, how to divide text into paragraphs content block with extra info.
see loadData function.
convertFromRaw function converts the content block, with entity map to add to draft.js.
import React from 'react';
import ReactDOM from 'react-dom';
import Draft, {
Editor,
EditorState,
ContentState,
convertFromRaw,
} from 'draft-js';
import './styles.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty(),
};
this.onChange = editorState => this.setState({ editorState });
}
loadData() {
const blocks = [
{
text: 'Lorem ipsum',
type: 'paragraph',
data: {
speaker: 'Foo',
},
entityRanges: [],
},
{
text: 'Dolor foo bar',
type: 'paragraph',
data: {
speaker: 'Bar',
},
entityRanges: [],
},
];
const entityMap = {};
const contentState = convertFromRaw({ blocks, entityMap });
const editorState = EditorState.createWithContent(contentState);
this.setState({ editorState });
}
render() {
return (
<div className="App">
<Editor editorState={this.state.editorState} onChange={this.onChange} />
<button onClick={() => this.loadData()}>load data</button>
</div>
);
}
}
const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);
The blocks,
textis the text displayed in the draft editortypecan beparagraph,header-oneetc.. see full list in docsdatais arbitrary date you can add yourself and keep associated with that text.entityRangesallows to identify entities in the text, using character's index. see note on draftjs entity range for more on this.
const blocks = [
{
text: 'Lorem ipsum',
type: 'paragraph',
data: {
speaker: 'Foo',
},
entityRanges: [],
},
{
text: 'Dolor foo bar',
type: 'paragraph',
data: {
speaker: 'Bar',
},
entityRanges: [],
},
];