'Manually Focusing a DraftJS Component Only Works the First Time
I have rendered a a React Draft WYSIWYG component using the following code:
InputTextArea.js (parent component in charge of managing focus()
import { useRef } from "react"
import EditorConvertToHTML from "./EditorConvertToHTML";
export default function InputTextArea({ editing }) { // this prop is a state variable passed from parent (setter function not needed here so not passed)
const editorRef = useRef()
useEffect(() => { // if user clicks a button which sets 'editing' to true, set focus to the rich text editor component
if(editing) {
editorRef.current.focus()
}
}, [editing])
return(
<EditorConvertToHTML
innerRef={editorRef}
readOnly={!editing}
/>
)
}
EditorConvertToHTML (actual rich text editor component
import { Component } from 'react';
import { EditorState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
export default class EditorConvertToHTML extends Component {
state = {
editorState: EditorState.createEmpty()
}
onEditorStateChange = (editorState) => {
this.setState({
editorState,
});
};
render() {
const { editorState } = this.state;
return (
<Editor
editorRef={(ref) => this.props.innerRef.current = ref}
editorState={editorState}
onEditorStateChange={this.onEditorStateChange}
readOnly={this.props.readOnly}
/>
);
}
}
The first time that editing is set to true, ReactJS successfully focuses EditorConvertToHTML component. However, when I set it to false and then again to true, the component no longer becomes focused.
I know that the useEffect and contained if(editing) conditions are triggered each time that editing is set to true because I have added a logger in there which confirmed it's being called. I get no errors in console.
Why is focus working only the first time that editing is set to true?
If there's any other information that you'd find helpful, please let me know.
Edit:
I logged the editorRef object into the console just before the focus() method gets called and see that the object of the variable is different between the first time (when focus() works) and second time (when focus() doesn't work), where first time it's a DraftEditor object, and second time it's a different object.
Why is the object in editorRef changing and is there a way I can ensure that focus() works every time that editing is set to true?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

