Skip to content

Instantly share code, notes, and snippets.

@lixiaoyan
Last active June 21, 2021 08:46
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lixiaoyan/79b5740f213b8526d967682f6cd329c0 to your computer and use it in GitHub Desktop.
Save lixiaoyan/79b5740f213b8526d967682f6cd329c0 to your computer and use it in GitHub Desktop.
Draft.js with line number.
.line {
position: relative;
}
.line::before {
content: attr(data-line-number);
position: absolute;
left: 0;
top: 0;
opacity: 0.5;
}
.line-text {
margin-left: 2em;
}
import React from "react";
import ReactDOM from "react-dom";
import { Editor, EditorBlock, EditorState } from "draft-js";
class Line extends React.Component {
render() {
const { block, contentState } = this.props;
const lineNumber =
contentState
.getBlockMap()
.toList()
.findIndex(item => item.key === block.key) + 1;
return (
<div className="line" data-line-number={lineNumber}>
<div className="line-text">
<EditorBlock {...this.props} />
</div>
</div>
);
}
}
const blockRendererFn = () => ({
component: Line,
});
class App extends React.Component {
state = {
editorState: EditorState.createEmpty(),
};
handleChange = editorState => {
this.setState({ editorState });
};
render() {
return (
<Editor
editorState={this.state.editorState}
onChange={this.handleChange}
blockRendererFn={blockRendererFn}
/>
);
}
}
ReactDOM.render(<App />, document.querySelector("#app"));
@schabluk
Copy link

This is very neat! Thanks!

@raph941
Copy link

raph941 commented Jun 21, 2021

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment