Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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')
)
@bummzack

This comment has been minimized.

Copy link

commented Apr 20, 2017

Found this via google. Thanks!
Have you found a solution to disable caret movement to the line-number? When I use up- and down-arrows on the keyboard, the text-cursor moves to the line-number.

@lixiaoyan

This comment has been minimized.

Copy link

commented May 31, 2017

@bummzack
https://gist.github.com/lixiaoyan/79b5740f213b8526d967682f6cd329c0
I made an example with ::before and it works fine in modern browsers. (I tested it in Chrome, Firefox, Edge and Safari)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.