Making bullet points in Draft.js
Asked Answered
C

2

7

I am using Draft.js to introduce a text editor to my React application. I have made it work for bold, italic and underline but I can't figure out how to change the text to bullet points. I have read the documentation but I couldn't find anything helpful. Can anyone please help?

Confront answered 2/9, 2016 at 13:38 Comment(0)
L
13

You can turn any text block to bullet points with RichUtils of draft-js. Here is how you can do it:

// button to turn text block to bullet points
<button onClick={this.toggleBulletPoints}>Bullet points</button>

toggleBulletPoints(){
    this.setState({
        editorState: RichUtils.toggleBlockType(
            this.state.editorState,
            'unordered-list-item'
        )
    })
}

Here is the complete example of to change inline styles and block types in draft-js editor: https://github.com/facebook/draft-js/blob/master/examples/draft-0-10-0/rich/rich.html

Lozier answered 14/9, 2016 at 10:41 Comment(1)
Doesn't indent the blocks though.Outgoing
D
2

I would just leave a comment but I don't have enough karma...

In the answer marked as correct, I'm not sure how that would work. It looks like state is being set incorrectly. Should it not be set like this:

<button onClick={this.toggleBulletPoints}>Bullet points</button>

toggleBulletPoints(){
    this.setState({
        editorState: RichUtils.toggleBlockType(
            this.state.editorState,
            'unordered-list-item'
        )
    })
}

I don't think you can directly save the output of a function to state without defining its key. At the very least, it doesn't work for me when I tried the answer marked as correct.

Also, since this was updated a year ago here is a more recent possible solution:

constructor(props) {
  super(props);
  this.state = {
    editorState: EditorState.createEmpty()
  };
}

onChange = (editorState) => {
  this.setState({
    editorState
  });
};

toggleBlockType = () => {
  this.onChange(
    RichUtils.toggleBlockType(this.state.editorSection, 'unordered-list-item')
  );
};

render() {
  return (
    <div>
      <Editor
        editorState={this.state.editorState}
        onChange={this.onChange}
      />
    </div>
  )
}

Hope this helps someone!

Dogcart answered 13/8, 2019 at 20:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.