Draft.js initiate with convertFromRaw method
Draft.js initiate with convertFromRaw method (for stackoverflow answer)
by Mikhail Shabrikov
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react-dom.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.7.0/Draft.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/draft-js/0.7.0/Draft.css">
<!-- Created for this stackoverflow answer - https://stackoverflow.com/a/47030806/5806646 -->
<div id="react-root"></div>
CSS
body {
font-family: Helvetica, sans-serif;
}
.container-root {
border: 1px solid black;
padding: 5px;
margin: 5px;
}
Babel + JSX
const {Editor, RichUtils, EditorState, convertFromRaw, convertToRaw} = Draft;
const customStyleMap = {
redBackground: {
backgroundColor: 'red'
},
underlined: {
textDecoration: 'underline',
fontSize: 26
},
};
const editorStateAsJSON = `{"entityMap":{},"blocks":[{"key":"fveh7","text":"fasdf","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[]},{"key":"10mi0","text":"asdf","type":"unstyled","depth":0,"inlineStyleRanges":[{"offset":2,"length":2,"style":"redBackground"}],"entityRanges":[]},{"key":"dnuro","text":"asdfasdf","type":"unstyled","depth":0,"inlineStyleRanges":[{"offset":4,"length":2,"style":"underlined"}],"entityRanges":[]}]}`;
class Container extends React.Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createWithContent(convertFromRaw(JSON.parse(editorStateAsJSON)))
};
}
applyCustomStyles = (nameOfCustomStyle) => {
this._handleChange(
RichUtils.toggleInlineStyle(
this.state.editorState,
nameOfCustomStyle
)
);
}
_handleChange = (editorState) => {
this.setState({ editorState });
}
render() {
return (
<div>
<div className="container-root">
<Editor
placeholder="Type away :)"
editorState={this.state.editorState}
onChange={this._handleChange}
customStyleMap={customStyleMap}
/>
</div>
<button onClick={() => this.applyCustomStyles('underlined')}>
apply one custom style to selected text
</button>
<button onClick={() => this.applyCustomStyles('redBackground')}>
apply anoter custom style to selected text
</button>
</div>
);
}
}
ReactDOM.render(<Container />, document.getElementById('react-root'))