Using AceEditor in React

sgpropguide
2 min readApr 2, 2019

--

AceEditor is a pretty cool editor — among other things, it supports Syntax highlighting for over 110 languages.

Nonetheless, using AceEditor in React comes with a few quirks.

AceEditor doesn’t display anything on using setState in onChange

I was frustrated when using setState in AceEditor’s onchange causes anything typed in the editor to not show at all — see the sentiments reflected in this post on what happened in my case.

The answer to the problem came in the form of this helpful stackoverflow post. I understood that using setState in onChange causes a re-render that wiped out the text displayed in the editor and that the trick was to store the value in state.

Taken from the helpful stackoverflow article — highlight is mine

AceEditor onChange function doesn’t take our own argument

Let say you have 100 input elements in your component and you want to capture the information in state when the user types in something in any of the 100 input elements.

You might want to start with the application state as an empty object ie.

constructor(props) {super(props);this.state = {content: {}};}

Then create 100 input elements with each input element having an id and we want to call setState to track the input value and tag the value to its element id.

Here’s an example in codesandbox:

Long story short, the trick lies in the [i] within these lines:

for (let i = 0; i < 20; i++) {<inputonChange={e =>{
let content = Object.assign({}, this.state.content, { [i]: e.target.value } );
this.setState({content})}}/>

In AceEditor, we can do something similar too. My use case was that users may create multiple text blocks — each block being an individual AceEditor component.

Although they are given one text block to edit when page loads initially, users can add as many text blocks they like. My goal was to create new AceEditors with separate names or IDs as users add new text blocks.

Therefore, i defined a function called Editor that returns AceEditor. The good thing provided by Editor is that it takes a name parameter allows us to spin up multiple Editors each with a unique name.

Subsequently, each time the text content in an Editor is modified, it gets stored in this.state.content.ITS-OWN-NAME.

--

--