JavaScript for WordPress › Forums › Gutenberg Development › Code Editor › Reply To: Code Editor
May 2, 2018 at 12:43 pm
#46111
R B ATTENBOROUGH
Participant
Managed to fix it 🙂 !
I had to pass the instance to the Inspector controls:
edit: props => {
const { attributes: { content, language, lineNumbers }, isSelected, setAttributes } = props;
return [
isSelected && (<Inspector { ...{setAttributes, ...props, ...{editor: this}} } />),
isSelected && (<Controls { ...{setAttributes, ...props, ...{editor: this}} } />),
<div>
<div>
<h4>Language: {language}</h4>
</div>
<CodeEditor editorRef={ ( ref ) => this.editorInstance = ref }
value={ content }
settings={Object.assign( {
codemirror: {
mode: language,
lint: true,
lineNumbers: lineNumbers,
} },
window._wpGutenbergCodeEditorSetting
) }
onChange={ ( content, language, lineNumbers ) => setAttributes( { content }, {language}, {lineNumbers}) }
/>
</div>
];
},
And then within the inspector control I used the editor prop to change the editor instance:
export default class Inspector extends Component {
constructor() {
super( ...arguments );
}
render() {
const { attributes: { language }, setAttributes, editor } = this.props;
function onChangeLanguage (language) {
setAttributes( { language } );
editor.editorInstance.setOption( 'mode', language );
}
return (
<InspectorControls>
<PanelBody
title={ __( 'Snippet settings', 'rba-codeblock' ) }
>
</PanelBody>
<PanelBody>
<RadioControl
label={ __( 'Language', 'rba-codeblock' ) }
selected={ language }
options={ [
{ label: 'HTML', value: 'htmlmixed' },
{ label: 'CSS', value: 'css' },
{ label: 'JS', value: 'javascript' }
] }
onChange={ onChangeLanguage }
/>
</PanelBody>
</InspectorControls>
);
}
}
So it finally all works! You can check out the github repo here: https://github.com/BenAttenborough/rba-codeblock
Be warned that this only works with the Gutenberg production code at the moment.