Created
July 5, 2017 19:30
-
-
Save scf4/bb49f9167d1c24357d5ee0a8bbb777de to your computer and use it in GitHub Desktop.
[Draft.js plugins] How to force block style on first line for a heading/title like Medium
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import and add to your Editor's plugins | |
import { RichUtils } from 'draft-js'; | |
const HEADING = 'header-one'; | |
export default () => ({ | |
onChange: (editorState) => { | |
const currentContent = editorState.getCurrentContent(); | |
const firstBlockKey = currentContent.getBlockMap().first().getKey(); | |
const currentBlockKey = editorState.getSelection().getAnchorKey(); | |
const isFirstBlock = (currentBlockKey === firstBlockKey); | |
const currentBlockType = RichUtils.getCurrentBlockType(editorState); | |
const isHeading = currentBlockType === HEADING; | |
if (isFirstBlock !== isHeading) { | |
return RichUtils.toggleBlockType(editorState, HEADING); | |
} | |
return editorState; | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment