How to insert spaces/tabs with onTab (Keydown keyCode=8 to action)
Use the onTab prop.
const MyComponent extends React.Component {
constructor(props) {
// etc.
this.onTab = this.onTab.bind(this);
}
onTab(e) {
// Use `Modifier` API to insert spaces
// e.preventDefault() if successful
this.setState({editorState: stateWithSpacesInserted});
}
render() {
return <Editor onTab={this.onTab} ... />;
}
}
Here's a more fleshed out example with the Modifier API, adapted from draft-js-code:
const tabCharacter = " ";
// ...
handleTab(e) {
e.preventDefault();
let currentState = this.state.editorState;
let newContentState = Modifier.replaceText(
currentState.getCurrentContent(),
currentState.getSelection(),
tabCharacter
);
this.setState({
editorState: EditorState.push(currentState, newContentState, 'insert-characters')
});
}
Just a note.
This won't work with auto indenting lists as tab is supposed too. It will actually break the functionality.
Just wanted to drop a fragment of code that addresses @voidstarfire 's concern about losing list functionality. The point is you check for the list BlockStyles before deciding what to do next.
onTab = (e) => {
e.preventDefault();
let currentState = this.state.editorState
const selection = currentState.getSelection();
const blockType = currentState
.getCurrentContent()
.getBlockForKey(selection.getStartKey())
.getType();
if(blockType === "unordered-list-item" || blockType === "ordered-list-item"){
this.handleChange(RichUtils.onTab(e, currentState, 3));
}else{
let newContentState = Modifier.replaceText(
currentState.getCurrentContent(),
currentState.getSelection(),
' '
);
this.handleChange(EditorState.push(currentState, newContentState, 'insert-characters'))
}
}
@MichaelCPell Could you explain what it does with lists? The code can't seem to work. But it does capture the tab on both list block types.
It defaults to the onTab behavior if your cursor is in a list.
In latest version "onTab" is deprectaed and it is said that we should use the stuff with the key / command dispatching - but I'm not sure how to put it together properly, bcs RichUtils wants the event in the onTab call which isn't around when you're handling commands...
Most helpful comment
Here's a more fleshed out example with the Modifier API, adapted from draft-js-code: