Short answer: Use a container component that holds the editor, button, and the added component.
React solves the problem of building networks of "things" that interact with Composition (as opposed to Inheritance). Create a stateful ("class-based") component, store "all the stuff that changes" inside that component's state
, and then you won't lose any data when components inside that component change. Pass data to child components as props.
The DraftJS documentation tells you how to store editor data in state
.
It will look something like this:
class Container extends React.Component {
constructor(props) {
this.state = {
editorState: EditorState.createEmpty(),
// Make sure 'MyComponent` is a React component defined in this file or imported from somewhere
addedComponentType: MyComponent,
showAddedComponent: false,
}
}
handleEditorChange = (editorState) => this.setState({editorState})
// shorthand for `this.setState({editorState: editorState})`
toggleShowAddedComponent = () => this.setState({
showAddedComponent: !this.state.showAddedComponent
})
render() {
const {addedComponentType: AddedComponent} = this.state
// Shorthand for `const AddedComponent = this.state.addedComponentType`
return (
<Editor editorState={this.state.editorState} onChange={this.handleEditorChange} />
{this.state.showAddedComponent && <AddedComponent>Hello World!</AddedComponent>}
<button onClick={this.toggleShowAddedComponent}>
{this.state.showAddedComponent ? 'Hide' : 'Show'} Added Component
</button>
)
}
}
Hello World !
. – Lucien Perouze Jan 29 '18 at 22:50