I'm trying to update the text from a calling component into the Editor component. I use the props to pass the text from the caller, but when the text change (props is updated in the ContentEditor) the text in the Editor component is not:
Here is the code of the calling component:
<ControlledEditor htmlContent={this.state.validationResultContent}/>
Here is the code of the Controlled Editor:
export class ControlledEditor extends Component {
constructor(props) {
super(props);
this.state = {editorState: EditorState.createWithText(this.props.htmlContent)};
}
onEditorStateChange = (editorState) => {
this.setState({ editorState })
};
render() {
const { editorState } = this.state;
return (
<>
<Container className="mt-5">
<Row>
<Editor
editorState= {editorState}
onEditorStateChange={this.onEditorStateChange}
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
/>
</Row>
</Container>
</>
);
}
}
ControlledEditor.propTypes = {
htmlContent: PropTypes.string
}
thanks for the help
------- UPDATE 1 -------
- I'm using react-draft-wysiwyg build onto Draft.js
- text to render is HTML so I updated the code
- answer from Linda Paiste with componentDidUpdate solves the main problem link
Following the working code (for me):
export class ControlledEditor extends Component {
constructor(props) {
super(props);
this.state = {editorState: EditorState.createEmpty()}
}
componentDidUpdate(prevProps) {
if (this.props.htmlContent !== prevProps.htmlContent) {
this.setState({
editorState: EditorState.createWithContent(ContentState.createFromBlockArray(convertFromHTML(this.props.htmlContent)))
});
}
}
onEditorStateChange = (editorState) => {
this.setState({editorState})
};
render() {
const {editorState} = this.state;
return (
<>
<Container className="mt-5">
<Row>
<Editor
editorState={editorState}
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
onEditorStateChange={this.onEditorStateChange}
/>
</Row>
</Container>
<Container className="mt-5">
<Row>
<div dangerouslySetInnerHTML={{__html: this.props.htmlContent}}/>
</Row>
</Container>
</>
);
}
}
ControlledEditor.propTypes = {
htmlContent: PropTypes.string
}