Draft.js editorState Fiddle
A fiddle to repro issues in Draft.js
by Juan Lanus
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">
<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
},
};
class Container extends React.Component {
constructor(props) {
super(props);
let initialEditorState = null;
const storeRaw = localStorage.getItem('draftRaw');
if (storeRaw) {
const rawContentFromStore = convertFromRaw(JSON.parse(storeRaw));
initialEditorState = EditorState.createWithContent(rawContentFromStore);
} else {
initialEditorState = EditorState.createEmpty();
}
this.state = {
editorState: initialEditorState
};
}
applyCustomStyles = (nameOfCustomStyle) => {
this._handleChange(
RichUtils.toggleInlineStyle(
this.state.editorState,
nameOfCustomStyle
)
);
}
saveRaw = () => {
var contentRaw = convertToRaw(this.state.editorState.getCurrentContent());
localStorage.setItem('draftRaw', JSON.stringify(contentRaw));
console.log( JSON.stringify(contentRaw, null, 2) );
}
_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 1 custom style to selected text
</button>
<button onClick={() => this.applyCustomStyles('redBackground')}>
apply 2 custom style to selected text
</button>
<div>
<button onClick={this.saveRaw}>
SAVE RAW CONTENT TO LOCAL STORAGE
</button>
</div>
</div>
);
}
}
ReactDOM.render(<Container />,...