Skip to content

Instantly share code, notes, and snippets.

@yornaath
Forked from schabluk/DraftLineNumbers.js
Created March 12, 2020 12:08
Show Gist options
  • Save yornaath/941630cd6e8223a61ed6174edf4a9e18 to your computer and use it in GitHub Desktop.
Save yornaath/941630cd6e8223a61ed6174edf4a9e18 to your computer and use it in GitHub Desktop.
Display line numbers is Draft-JS Editor
// Required Draf-js version: 0.10.
// Live example: https://jsfiddle.net/schabluk/gh2gt22n/
import React from 'react'
import ReactDOM from 'react-dom'
import {Editor, EditorState, EditorBlock} from 'draft-js'
class Line extends React.Component {
render () {
const blockMap = this.props.contentState.getBlockMap().toArray()
const blockKey = this.props.block.key
const lineNumber = blockMap.findIndex(block => blockKey === block.key) + 1
return <div style={{display: 'flex'}}>
<span style={{marginRight: '5px'}}>{lineNumber}</span>
<div style={{flex: '1'}}><EditorBlock {...this.props} /></div>
</div>
}
}
const blockRendererFn = function(contentBlock) {
const type = contentBlock.getType()
switch (type) {
default:
return {component: Line, editable: true}
}
}
class App extends React.Component {
constructor (props) {
super(props)
const editorState = EditorState.createEmpty()
this.state = {editorState}
this.onChange = this.onChange.bind(this)
}
onChange (editorState) {
this.setState({editorState})
}
render () {
return <div style={{backgroundColor: '#fff'}}>
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
blockRendererFn={blockRendererFn}
/>
</div>
}
}
ReactDOM.render(
<App />,
document.getElementById('react-root')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment