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?
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
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!
© 2022 - 2024 — McMap. All rights reserved.