codeslayer1 / react-ckeditor

CKEditor component for React with plugin and custom event listeners support
MIT License
129 stars 34 forks source link

Can we set editor to readOnly based on state? #51

Closed gurnzbot closed 6 years ago

gurnzbot commented 6 years ago

Is there a way to set the component as readOnly? I've tried to set the config property readOnly using a state property called submitLoading that will be true or false.

It seems that dynamically using state to set this property won't change the property since the component is already initialized.

Here's what I got goin on:

<CKEditor
    scriptUrl="/ckeditor/ckeditor.js"
    content={data.notes}
    config={{
        removePlugins: "elementspath,uploadimage,uploadfile",
        toolbar: "None",
        readOnly: submitLoading
    }}
    events={{ instanceReady: editorReady.bind(this), change: this.editorChange.bind(this) }}
 />

Any ideas?

codeslayer1 commented 6 years ago

If you use config property to set readOnly, it will only work during the initialisation.

If you want to toggle the readOnly mode dynamically, you can keep a reference to the CKEditor and use it to toggle the editor whenever the submitLoading property changes. Here is a sample code.

//call this function whenever your submitLoading property changes
setReadOnly(){
    this.ckeditor.editorInstance.setReadOnly(submitLoading);
}

<CKEditor
       ref={instance => {this.ckeditor = instance;}}
gurnzbot commented 6 years ago

Makes all of the sense! I am lame for not realizing this. Thank you! <3

gurnzbot commented 6 years ago

I'm running into an issue where the ref is not set correctly at times. I think it is due to server-side rendering, and the ref being set before the CKEditor script is loaded, but that is straight-up a guess. This issue is very sporadic and happens maybe once every 15 times I try it.

The error states: Cannot read property 'setReadOnly' of undefined and points to the line this.ckeditor.editorInstance.setReadOnly(this.state.submitLoading);

Is there a way to deal with this editorInstance being undefined? I have a feeling it's totally obvious but I'm not seeing it.

codeslayer1 commented 6 years ago

It is quite possible that you are setting the readOnly property before the component has fully loaded. I think you can simply add a check for reference not to be undefined before setting the property.

Also, you can pass the initial readOnly property value via config so that your component initialises in the correct state and then once you get the reference, you can easily update the property thereafter.

codeslayer1 commented 6 years ago

Closing this issue due to no further activity.